Skip to main content

Logging

Logging providers store logs, except for the Console provider which displays logs. For example, the Azure Application Insights provider stores logs in Azure Application Insights. Multiple providers can be enabled.

The default ASP.NET Core web app templates call WebApplication.CreateBuilder, which adds the following logging providers:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
...

The following code overrides the default set of logging providers added by WebApplication.CreateBuilder:

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddConsole();

Alternatively, the preceding logging code can be written as follows:

var builder = WebApplication.CreateBuilder();
builder.Host.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
});

Configure logging

Logging configuration is commonly provided by the Logging section of appsettings.{ENVIRONMENT}.json files, where the {ENVIRONMENT} placeholder is the environment. The following appsettings.Development.json file is generated by the ASP.NET Core web app templates:

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

In the preceding JSON:

  • The "Microsoft.AspNetCore" category applies to all categories that start with "Microsoft.AspNetCore". For example, this setting applies to the "Microsoft.AspNetCore.Routing.EndpointMiddleware" category.
  • The "Microsoft.AspNetCore" category logs at log level Warning and higher.
  • A specific log provider is not specified, so LogLevel applies to all the enabled logging providers (except for the Windows EventLog).

The LogLevel specifies the minimum level to log for selected categories. LogLevel indicates the severity of the log and ranges from 0 to 6:

Trace = 0, Debug = 1, Information = 2, Warning = 3, Error = 4, Critical = 5, and None = 6.

If no LogLevel is specified, logging defaults to the Information level. A provider property can specify a LogLevel property. LogLevel under a provider specifies levels to log for that provider, and overrides the non-provider log settings. A more complex appsettings.json file can look like this:

{
"Logging": {
"LogLevel": {
// All providers, LogLevel applies to all the enabled providers.
"Default": "Error", // Default logging, Error and higher.
"Microsoft": "Warning" // All Microsoft* categories, Warning and higher.
},
"Debug": {
// Debug provider.
"LogLevel": {
"Default": "Information", // Overrides preceding LogLevel:Default setting.
"Microsoft.Hosting": "Trace" // Debug:Microsoft.Hosting category.
}
},
"EventSource": {
// EventSource provider
"LogLevel": {
"Default": "Warning" // All categories of EventSource provider.
}
}
}
}