LogInformation is an ILogger extension method for recording an Information-level message. The logger sends the message to every configured logging provider. section 26.2
Use LogInformation with these practical rules:
- Inject ILogger<T> into a class through dependency injection, then call LogInformation with a message template and its values. section 26.2
- Prefer named placeholders such as {RecipeCount} over string interpolation; logging can retain the named value for structured analysis. section 26.2 section 26.6
- Expect the final presentation to vary by provider; console, debug, EventLog, and EventSource providers are available in ASP.NET Core. section 26.2 section 26.6
Logging the number of loaded recipes
An IndexModel injects ILogger<IndexModel>, loads recipes in OnGet, and records the result with _log.LogInformation("Loaded {RecipeCount} recipes", Recipes.Count). The provider can display the substituted message while retaining RecipeCount as structured data. section 26.2
Listing 26.2 Injecting ILogger into a class and writing a log message
public class IndexModel : PageModel
{
private readonly RecipeService _service;
private readonly ILogger<IndexModel> _log; #1
public ICollection<RecipeSummaryViewModel> Recipes { get; set; }
public IndexModel(
RecipeService service,
ILogger<IndexModel> log) #1
{
_service = service;
_log = log; #1
}
public void OnGet()
{
Recipes = _service.GetRecipes();
_log.LogInformation( #2
"Loaded {RecipeCount} recipes", Recipes.Count); #2
}
}
#1 Injects the generic ILogger<T> using DI, which implements ILogger
#2 Writes an Information-level log. The RecipeCount variable is substituted in the message.
View the complete Razor Page example showing dependency injection, the LogInformation call, and placeholder substitution. section 26.2
