Published on: June 11, 2025
Category: Tutorial Tuesday
Tags: Serilog, ASP.NET Core, Logging, Middleware, .NET Core, Dev Tutorial, .NET Dev Corner, Application Insights
๐ What is Serilog?
Serilog is a structured logging library for .NET that lets you write logs to multiple outputs (called sinks) in a clean, readable format. It’s ideal for production-grade applications and supports powerful features like filtering, enrichers, and asynchronous logging.
⚙️ Step 1: Install Required Packages
Use the following NuGet packages to integrate Serilog in an ASP.NET Core project:
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;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
var builder = WebApplication.CreateBuilder(args);
// Use Serilog
builder.Host.UseSerilog();
var app = builder.Build();
app.Run();
๐ This config writes logs to both the console and a rolling file.
๐งช Step 3: Test Logging
Add this line in any controller or middleware:
Log.Information("This is a test log at {Time}", DateTime.Now);
You’ll see structured output like:
[12:42:30 INF] This is a test log at 6/10/2025 12:42:30 PM
๐งฉ Step 4: Add Enrichers (Optional)
To enrich logs with extra context like thread or process ID:
dotnet add package Serilog.Enrichers.Thread
dotnet add package Serilog.Enrichers.Process
Log.Logger = new LoggerConfiguration()
.Enrich.WithThreadId()
.Enrich.WithProcessId()
.WriteTo.Console()
.CreateLogger();
๐ Bonus: Send Logs to Application Insights or Seq
Use additional sinks for cloud monitoring:
dotnet add package Serilog.Sinks.ApplicationInsights
dotnet add package Serilog.Sinks.Seq
Then configure accordingly for scalable observability.
๐ Why Use Serilog?
Feature | Benefit |
---|---|
Structured logs | Queryable in tools like Seq, ELK |
Multi-sinks | Write to console, files, DBs, or cloud |
Enrichers | Add custom properties (e.g., request ID) |
Performance | Asynchronous support for non-blocking logs |
๐ก Final Thoughts
If you’re not logging, you’re debugging blind. Serilog makes logging simple, powerful, and production-ready for .NET developers.
Start with console and file sinks. Then scale to cloud tools as your app grows.
๐ฌ Stay Connected
- ๐ Blog: www.ajaygangwar.com
- ๐ผ LinkedIn: Ajay Gangwar
- ๐ง Email: seajaygangwar@gmail.com