Logging in .NET Core: Built-in Logging vs Serilog with Full Implementation Guide
Logging in .NET Core: Built-in Logging vs Serilog with
Full Implementation Guide
Logging is an essential aspect of application development.
In .NET Core and beyond (.NET 5/6/7/8), Microsoft provides a built-in logging
framework that is simple to use. However, when applications grow and logging
needs become more advanced, third-party solutions like Serilog shine. In this
blog, we will explore built-in logging, Serilog, their differences, and how to
implement both in your .NET Core application.
1. .NET Core Built-in Logging Overview
.NET Core uses Microsoft.Extensions.Logging as a base
logging interface. This logging abstraction allows logging to multiple
destinations, such as:
- Console
- Debug
- EventSource
- EventLog
(Windows only)
- Azure
Application Insights (via extensions)
- Files
(through third-party integrations)
Pros:
- Simple
to use
- Built-in
- Fully
integrated with Dependency Injection (DI)
Cons:
- Limited
formatting options
- No
structured logging out-of-the-box
2. What is Serilog?
Serilog is a powerful, structured logging library designed
for .NET applications. It focuses on structured log events with properties and
values, making logs more readable and machine-parsable.
Pros:
- Structured
logging (key-value pair logs)
- Rich
and extensible sinks (File, SQL, Elasticsearch, Seq, etc.)
- Advanced
formatting and enrichment
- Asynchronous
logging support
Cons:
- Requires
additional setup and packages
3. Key Differences
Feature |
Built-in Logging |
Serilog |
Structured logging |
No |
Yes |
Formatting |
Basic |
Highly customizable |
Output targets (sinks) |
Limited |
Extensive |
File logging |
Not built-in |
Easy via Serilog sinks |
Async support |
No |
Yes |
Integrated with DI |
Yes |
Yes |
4. Implementation Examples
A. Using Built-in Logging
// Program.cs (.NET 6+)
var builder = WebApplication.CreateBuilder(args);
// Configure built-in logging
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
var app = builder.Build();
app.MapGet("/", (ILogger<Program> logger)
=>
{
logger.LogInformation("Request received at /");
return "Hello
World!";
});
app.Run();
B. Using Serilog with Console and File Logging
Step 1: Install Required Packages
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.File
Step 2: Configure Serilog in Program.cs
using Serilog;
var builder = WebApplication.CreateBuilder(args);
// Setup Serilog
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("Logs/log-.txt", rollingInterval:
RollingInterval.Day)
.Enrich.FromLogContext()
.MinimumLevel.Debug()
.CreateLogger();
builder.Host.UseSerilog();
var app = builder.Build();
app.MapGet("/", (ILogger<Program> logger)
=>
{
logger.LogInformation("Handled GET /");
return "Hello
from Serilog!";
});
app.Run();
5. Optional: Serilog with appsettings.json
Step 1: Add Additional Packages
dotnet add package Serilog.Settings.Configuration
Step 2: Configure appsettings.json
"Serilog": {
"MinimumLevel": "Debug",
"WriteTo":
[
{
"Name": "Console" },
{
"Name": "File",
"Args": {
"path": "Logs/log-.txt",
"rollingInterval": "Day"
}
}
],
"Enrich":
[ "FromLogContext" ]
}
Step 3: Update Program.cs
var builder = WebApplication.CreateBuilder(args);
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.CreateLogger();
builder.Host.UseSerilog();
6. Logging Exceptions with Serilog
Logging exceptions is critical for diagnosing issues in
production. Serilog provides excellent support for capturing exceptions with
full stack traces.
Example: Logging Exceptions in a Try-Catch Block
app.MapGet("/error", () =>
{
try
{
throw new
InvalidOperationException("Something went wrong!");
}
catch (Exception
ex)
{
Log.Error(ex,
"An error occurred while processing the request.");
return
Results.Problem("An unexpected error occurred.");
}
});
Tip: Capture Unhandled Exceptions
try
{
Log.Information("Starting up...");
var app =
builder.Build();
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex,
"Application terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
7. Conclusion
Built-in logging is great for simple applications and quick setup, but as logging requirements grow, Serilog offers more flexibility, structured logs, and support for multiple advanced output sinks. With Serilog, you can build robust and maintainable logging infrastructures tailored for production.
Comments
Post a Comment