Previous lesson: 🧱 Lecture 11: Continuous Integration and Continuous Deployment (CI/CD) with Jenkins
🎯 Introduction
Logging is the eyes and ears of your application. When things go wrong in production, a well-structured log file is often the only thing standing between a quick fix and a sleepless night. In this guide, we'll walk through implementing Serilog in a .NET 8 Web API, configuring it to write structured JSON logs to separate files for Error, Information, and Debug levels.
Why Serilog?
Serilog is a diagnostic logging library for .NET applications. Unlike default logging, Serilog is built from the ground up to support structured data. This means your logs aren't just text strings; they are data objects that can be easily queried, filtered, and analyzed.
Step 1: Install the Essentials
First, we need to add the necessary NuGet packages to our project. These packages allow Serilog to integrate with ASP.NET Core, write to files, and format logs as JSON.
Run the following commands in your project directory:
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.File
dotnet add package Serilog.Formatting.CompactSerilog.AspNetCore: Integrates Serilog with the ASP.NET Core framework.
Serilog.Sinks.File: Writes log events to files.
Serilog.Formatting.Compact: Formats logs as compact JSON, saving space and making them machine-readable.
Step 2: Configuration Magic
One of the most powerful features of Serilog is its ability to be configured entirely via appsettings.json. We want to separate our logs into three distinct files based on severity:
Error-yyyyMMdd.json: Critical issues that need immediate attention.
Info-yyyyMMdd.json: General application flow and operational events.
Debug-yyyyMMdd.json: Detailed diagnostic information for development and troubleshooting.
Open your
appsettings.json
and replace the default Logging section with this Serilog configuration:
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "logs/Error-.json",
"restrictedToMinimumLevel": "Error",
"rollingInterval": "Day",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
}
},
{
"Name": "File",
"Args": {
"path": "logs/Info-.json",
"restrictedToMinimumLevel": "Information",
"rollingInterval": "Day",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
}
},
{
"Name": "File",
"Args": {
"path": "logs/Debug-.json",
"restrictedToMinimumLevel": "Debug",
"rollingInterval": "Day",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
}
}
]
}
}

Join the conversation! Your thoughts help the community grow.