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
