liveBook · Manning

LoggerMessage

As explained in ASP.NET Core in Action, 3e

LoggerMessage is a .NET attribute that declares logging event metadata and a message template for source-generated logging methods.

LoggerMessage declares logging metadata and a message template for a source-generated partial method. The generator substitutes method parameters into the template and produces optimized logging code. section 26.2

Logging loaded recipes

A page model can declare LogLoadedRecipes with event ID 10, Information level, and the template "Loaded {RecipeCount} recipes". OnGet calls the method with Recipes.Count, which fills the template at runtime. section 26.2

[LoggerMessage(10, LogLevel.Information, "Loaded {RecipeCount} recipes")]
partial void LogLoadedRecipes(int recipeCount);
 
public void OnGet()
{
    Recipes = _service.GetRecipes();
    LogLoadedRecipes(Recipes.Count);
}

Use the complete declaration and OnGet call as a compact source-generated logging pattern. section 26.2

The attribute and generator provide:

  • An event ID, log level, and message template. section 26.2
  • Analyzers that check usage while generated code reduces allocations where possible. section 26.2
  • An optional alternative to ordinary ILogger logging, useful for avoiding accidentally interpolated strings. section 26.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains metadata, parameter substitution, analyzers, and allocation optimization, but defers configuration and generator internals.
Examples
Demonstrates logging a recipe count from an ASP.NET page model with a generated LogLoadedRecipes method.
What it assumes
Assumes ILogger-based logging and partial methods while introducing source generators as an optional compiler feature.
What you can do after
Apply it via the .NET logging source generator to define efficient, parameterized logging methods.
How it connects
Connects source generators, ILogger, partial methods, message templates, log levels, EventId, and analyzers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.