Introduction
In the previous lesson, we examined the fundamentals of ASP.NET Core logging, the ILogger abstraction, and logging categories. In this lesson, we will move from the default logging provider configuration to a Serilog-based setup. The goal is not simply to write messages to the console. We want to manage application logs, framework logs, and environment-specific behavior in a centralized and predictable way.
Serilog.AspNetCore routes log messages produced by ASP.NET Core through Serilog. As a result, the ILogger<T> interfaces used in application code can use the same levels, enrichers, and destinations processed by Serilog. This creates a foundation for adding file logging, centralized logging, request logging, and structured events in later lessons.
The examples assume a .NET 8 or newer ASP.NET Core Web API project using the modern minimal hosting model. Choose a Serilog.AspNetCore version compatible with the target framework of your application.
1. The main parts of Serilog configuration
Serilog configuration can be understood through three main areas:
- Minimum level: Determines which events are processed.
- Override rules: Change the general level for specific namespaces or logging categories.
- Sinks and destinations: Determine where processed events are written, such as the console, a file, or a centralized log system.
Serilog levels range from the most detailed to the most critical: Verbose, Debug, Information, Warning, Error, and Fatal. If the minimum level is Information, Information, Warning, Error, and Fatal events are accepted while Debug and Verbose events are filtered out.
ASP.NET Core framework components can produce a large number of log events. Therefore, a common starting point is to keep the application default at Information and raise the Microsoft and System categories to Warning.
2. Adding the packages
Run the following commands in the directory containing the existing API project:
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Settings.Configuration
dotnet add package Serilog.Sinks.ConsoleSerilog.AspNetCore provides the ASP.NET Core host integration. Serilog.Settings.Configuration allows Serilog settings to be read from appsettings.json. Serilog.Sinks.Console sends the example events to the console.
When selecting package versions, consider the target framework of the application. For example, using a compatible 8.x Serilog.AspNetCore release in a .NET 8 project helps reduce dependency mismatches.
3. Basic configuration in appsettings.json
Add a Serilog section to the appsettings.json file in the project root. The following configuration accepts application events from Information onward and raises framework events to Warning.
{
"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext} {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext" ],
"Properties": {
"Application": "Observability.Api"
}
}
}The Using section explicitly identifies the sink assembly used by the configuration. The WriteTo section defines the Console sink. The outputTemplate controls the text format of console output. SourceContext shows the category or class that produced the event, which is especially useful when reducing unnecessary framework logs.
FromLogContext allows properties added later through BeginScope or Serilog's LogContext to flow into log events. The Application property adds an application identifier to every event.
4. Enabling Serilog in Program.cs
Configure Serilog before the host is built and connect it to the ASP.NET Core logging pipeline:
using Serilog;
var builder = WebApplication.CreateBuilder(args);
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.CreateLogger();
builder.Host.UseSerilog();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
try
{
Log.Information("Application is starting");
app.Run();
}
catch (Exception exception)
{
Log.Fatal(exception, "Application stopped unexpectedly");
}
finally
{
Log.CloseAndFlush();
}ReadFrom.Configuration reads the Serilog section and creates the minimum levels and sinks. UseSerilog makes Serilog the provider used by the ASP.NET Core host. Creating Log.Logger before building the host is important because startup failures can occur before the host is fully available.
The try/catch/finally block records critical startup or shutdown failures with Fatal. Log.CloseAndFlush() gives buffered events an opportunity to reach their sinks before the application exits.
5. Environment-specific settings
ASP.NET Core configuration commonly loads appsettings.json first and then the matching appsettings.{Environment}.json file. To see more detailed logs during development, configure appsettings.Development.json as follows:
{
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Information",
"Microsoft.AspNetCore": "Information",
"System": "Information"
}
}
}
}For a production-like environment, use a more controlled configuration:
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.AspNetCore": "Warning",
"System": "Warning"
}
}
}
}When these files are combined, values in the environment-specific file complete or override values from the base file. Shared sink definitions can remain in the base file while minimum levels vary by environment. Enabling Debug permanently in production can create unnecessary volume and cost under high traffic, so use it deliberately.
6. Understanding category overrides
Override keys work as category prefixes. For example, the Microsoft.AspNetCore setting also applies to more specific categories that begin with that prefix. You can define a separate level for your own namespace:
"Override": {
"Microsoft": "Warning",
"Microsoft.AspNetCore": "Warning",
"Observability.Api.Controllers": "Debug"
}This reduces framework noise while allowing your own controller logs to be inspected at Debug level during development. Avoid setting a very broad namespace to Debug unless there is a clear reason, because it may produce many more events than expected.
7. Testing application logs
Use ILogger<HealthController> inside a controller or endpoint to verify that the levels behave as expected:
[ApiController]
[Route("api/health")]
public sealed class HealthController : ControllerBase
{
private readonly ILogger<HealthController> _logger;
public HealthController(ILogger<HealthController> logger)
{
_logger = logger;
}
[HttpGet]
public IActionResult Get()
{
_logger.LogDebug("Detailed diagnostic message for the health check");
_logger.LogInformation("Health check succeeded");
_logger.LogWarning("Sample warning message");
return Ok(new { status = " healthy " });
}
}In Development, all three messages should be visible. With an Information minimum level, the Debug event should disappear while the Information and Warning events remain. This test verifies not only that the endpoint works, but also that the configuration is active.
Run the application to inspect startup output:
dotnet runCheck the application name, timestamp, level, and source category in the console. Then deliberately introduce an invalid Serilog setting. For example, change the sink name to Consol and observe how configuration loading fails. Review when the application stops and where the error is reported. Restore the correct setting after the test.
8. Handling configuration failures safely
Typos, missing packages, invalid sink names, and unsupported log levels can prevent an application from starting. This is why the bootstrap logger should be created before the host is built. The startup catch block should run at a point where Serilog is already available whenever possible.
If you want to override configuration through environment variables, use the platform-independent hierarchy separator supported by ASP.NET Core. For example:
Serilog__MinimumLevel__Default=DebugThe double underscore represents a nested configuration section. In production, restrict permissions for people or processes that can change the minimum level externally.
Common mistakes
- Forgetting
UseSerilog: The packages may be installed, but ASP.NET Core can continue using the default providers. - Omitting
Serilog.Settings.Configuration: TheReadFrom.Configurationextension or configuration loading will not work as expected. - Using the wrong JSON hierarchy: The
Serilogsection must be at the root level. - Changing only the application level: Framework noise may continue unless framework categories are overridden.
- Leaving Debug enabled in production: This can unnecessarily increase disk, network, and centralized logging costs.
- Skipping the bootstrap logger: Errors that occur before host creation may be lost.
- Passing exceptions as ordinary message values: Use
_logger.LogError(exception, "...")so the stack trace is recorded as exception data.
Short practice exercise
- Add Serilog.AspNetCore, Serilog.Settings.Configuration, and Serilog.Sinks.Console.
- Set the default level to Information and the Microsoft level to Warning in
appsettings.json. - Set your own namespace to Debug in the Development configuration file.
- Add
ReadFrom.Configuration,UseSerilog, and the startuptry/catch/finallystructure to Program.cs. - Generate Debug, Information, and Warning events from an endpoint.
- Compare visible events in Development and Production-like environments.
- Break a sink name intentionally, observe the startup failure, and restore the correct setting.
Conclusion
In this lesson, we connected Serilog to the ASP.NET Core host lifecycle and moved configuration from code into appsettings.json. Minimum levels, category overrides, environment-specific files, and startup logging now provide controlled management of the application's logging behavior.
In the next lessons, we will extend this foundation with structured logging and additional sinks. Producing JSON events, writing to files or centralized systems, and adding request context will all build on the configuration established here.