Published on: June 3, 2025
Category: Tutorial Tuesday
Tags: ASP.NET Core, Serilog, Logging, .NET Core, Middleware, Application Insights, Dev Tutorial
🔧 Why Use Serilog?
- Easy syntax and configuration
- Powerful structured logging
- Multiple output sinks (Console, File, Seq, Azure Monitor, etc.)
- Support for filtering, theming, and JSON output
🚀 Step-by-Step Integration in ASP.NET Core
1️⃣ Install Required Packages
Use NuGet Package Manager or .NET CLI:
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.File
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);
builder.Host.UseSerilog(); // <-- Register Serilog
var app = builder.Build();
app.Run();
3️⃣ Verify It Works
Run the app and check the console or logs/log.txt
. Example output:
[10:32:45 INF] HTTP GET /api/products responded 200 in 150ms
🔍 Optional: Add Enrichers
Add context like thread ID, process ID, etc.:
using Serilog.Enrichers.Process;
using Serilog.Enrichers.Thread;
Log.Logger = new LoggerConfiguration()
.Enrich.WithProcessId()
.Enrich.WithThreadId()
.WriteTo.Console()
.CreateLogger();
⚙️ Use Cases in Real-World Apps
- Track API response times
- Log unhandled exceptions
- Send logs to centralized services like Seq or Azure Monitor
- Correlate logs with request IDs in distributed systems
📌 Final Thoughts
Serilog is beginner-friendly but scalable for production. If you're not yet using structured logging in ASP.NET Core—this guide should help you get started today.
📬 Stay Connected
- 🔗 Blog: www.ajaygangwar.com
- 💼 LinkedIn: Ajay Gangwar
- 📧 Email: seajaygangwar@gmail.com