Logging is an essential part of modern software development. Enterprise applications need reliable logging systems to monitor application behavior, identify problems, analyze performance, and maintain system reliability.
As ASP.NET Core applications grow, simple text-based logs are often not enough. Development teams require structured, searchable, and meaningful log data that can be analyzed across different environments.
Serilog is a powerful logging library for .NET applications that provides structured logging capabilities and integrates easily with ASP.NET Core.
What is Serilog?
Serilog is an open-source logging framework designed specifically for modern .NET applications. It allows developers to write log messages as structured events instead of plain text.
Unlike traditional logging approaches, Serilog stores information in a format that can be easily searched, filtered, and analyzed.
Traditional Logging Example
Console.WriteLine("User John logged into system");
The above message contains information, but searching and analyzing this data becomes difficult.
Structured Logging Example with Serilog
Log.Information("User {UserName} logged into system", userName);
In structured logging, the user name becomes a searchable property instead of just text inside a message.
Why Use Serilog in ASP.NET Core?
ASP.NET Core includes built-in logging support through Microsoft.Extensions.Logging. Serilog extends this capability with advanced features required for enterprise applications.
Major Benefits of Serilog
- Structured logging support
- Multiple output destinations
- Better debugging experience
- Easy integration with monitoring tools
- Centralized log management
- Production-ready performance
Built-in Logging vs Serilog
| ASP.NET Core Logging | Serilog |
|---|---|
| Basic logging abstraction | Advanced structured logging |
| Limited storage options | Many external sinks available |
| Simple application logs | Enterprise monitoring support |
| Less customization | Rich configuration options |
Serilog Architecture Overview
Serilog follows a pipeline-based architecture where log events flow through different components before reaching their final destination.
Application -> ILogger / Serilog -> Enrichers -> Sinks -> Storage / Monitoring System
Serilog Core Components
1. Logger
The logger creates log events from application activities.
2. Sinks
Sinks define where logs are stored or displayed.
Examples:
- Console
- File
- Database
- Seq
- Cloud monitoring systems
3. Enrichers
Enrichers add additional information to log events.
Examples:
- Machine name
- Application name
- Environment
- Request ID
Installing Serilog in ASP.NET Core
First, install the required NuGet packages.
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.File
Basic Serilog Configuration
Serilog can be configured inside the ASP.NET Core application startup process.
using Serilog;
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("logs/app.log")
.CreateLogger();
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog();
Serilog Configuration Using appsettings.json
For production applications, configuring Serilog through appsettings.json is usually preferred because it allows logging behavior to change without modifying application code.
appsettings.json Example
{
"Serilog": {
"Using": [
"Serilog.Sinks.Console",
"Serilog.Sinks.File"
],
"MinimumLevel": {
"Default": "Information",
"Microsoft": "Warning"
},
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path":"logs/application.log",
"rollingInterval":"Day"
}
}
]
}
}
This configuration writes logs to both the console and daily rotating log files.
Log Levels in Serilog
Log levels determine the importance and severity of application events.
| Level | Purpose |
|---|---|
| Verbose | Detailed diagnostic information |
| Debug | Developer troubleshooting information |
| Information | Normal application workflow events |
| Warning | Unexpected situations that do not stop execution |
| Error | Application failures and exceptions |
| Fatal | Critical failures requiring immediate attention |
Using ILogger with Serilog
ASP.NET Core applications can continue using the built-in ILogger abstraction. Serilog automatically becomes the logging provider behind it.
Service Logging Example
public class OrderService
{
private readonly ILogger<OrderService> _logger;
public OrderService(ILogger<OrderService> logger)
{
_logger = logger;
}
public void CreateOrder()
{
_logger.LogInformation("Creating new order");
}
}
Using ILogger keeps application code flexible because logging implementation details remain separated.
Structured Logging with Serilog
Structured logging is one of the most important features of Serilog. Instead of creating plain text messages, application data is stored as properties.
Traditional Logging
Log.Information("Order 5001 created by Ahmed");
The above message is difficult to search because order information is part of the text.
Structured Logging
Log.Information("Order {OrderId} created by {CustomerName}",5001,"Ahmed");
Now OrderId and CustomerName become searchable fields.
Logging Objects with Serilog
Serilog can capture complete objects as structured data.
var order = new {
Id = 1001,
Customer = "Ali",
Amount = 2500
};
Log.Information("Order created {@Order}", order);
The @ symbol tells Serilog to serialize the object properties.
Exception Logging in ASP.NET Core
Production applications must capture exceptions with enough information for troubleshooting.
Exception Logging Example
try
{
ProcessPayment();
}
catch(Exception ex)
{
_logger.LogError(ex, "Payment processing failed");
}
Serilog captures exception details including message, stack trace, and additional context.
Global Exception Handling Middleware
A centralized exception handling middleware ensures unexpected errors are logged consistently.
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch(Exception ex)
{
Log.Error(ex, "Unhandled application exception");
throw;
}
}
}
HTTP Request Logging with Serilog
ASP.NET Core applications often need information about incoming requests, responses, execution time, and status codes.
Serilog provides built-in middleware support for request logging.
Enable Request Logging
app.UseSerilogRequestLogging();
Example output:
HTTP POST /api/orders
StatusCode: 201
Elapsed: 120ms
Rolling File Logging
Applications running in production should avoid unlimited log file growth. Serilog supports rolling files based on time intervals.
Daily Rolling Logs
.WriteTo.File("logs/application-.txt", rollingInterval:RollingInterval.Day)
This creates separate files automatically:
application-2026-08-01.txt
application-2026-08-02.txt
application-2026-08-03.txt
Log Filtering
Not every framework message is useful in production. Serilog allows filtering logs by category and severity.
Example
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
This reduces unnecessary framework logs while keeping important application events.
Database Logging with Serilog
For enterprise applications, storing logs in a database can make searching, reporting, and auditing easier. Serilog supports database logging through additional sinks.
Installing SQL Server Sink
dotnet add package Serilog.Sinks.MSSqlServer
SQL Server Logging Configuration
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.MSSqlServer(connectionString:"Server=localhost;Database=Logs;Trusted_Connection=True", sinkOptions:
new MSSqlServerSinkOptions
{
TableName = "ApplicationLogs",
AutoCreateSqlTable = true
}
)
.CreateLogger();
The above configuration automatically creates a log table and stores application events in SQL Server.
Example Log Table Data
| Column | Purpose |
|---|---|
| Timestamp | Time when the event occurred |
| Level | Log severity |
| Message | Log description |
| Exception | Error details |
| Properties | Structured metadata |
Logging with Seq
Seq is a centralized log server designed for structured logging. It provides a user interface for searching, filtering, and analyzing Serilog events.
Install Seq Sink
dotnet add package Serilog.Sinks.Seq
Seq Configuration Example
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.Seq("http://localhost:5341")
.CreateLogger();
Developers can search logs using properties instead of manually reading text files.
Cloud Logging Integration
Modern applications often run on cloud platforms where centralized logging is important.
Serilog can send logs to various cloud monitoring solutions through available sinks.
Common Cloud Logging Destinations
- Azure Application Insights
- Amazon CloudWatch
- Google Cloud Logging
- Elastic Stack
Custom Enrichers in Serilog
Enrichers add additional information to every log event automatically.
Common examples include:
- Machine name
- Environment name
- Application version
- User information
- Correlation identifier
Adding Built-in Enrichers
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithEnvironmentName()
.WriteTo.Console()
.CreateLogger();
Correlation ID Logging
Distributed applications need a way to track a request across different components. A correlation ID helps connect related log entries together.
Correlation Flow
Client Request -> API Gateway -> ASP.NET Core API -> Database / External Services -> Logs with Same Correlation ID
Adding Correlation ID Middleware
public class CorrelationMiddleware
{
private readonly RequestDelegate _next;
public CorrelationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var correlationId = Guid.NewGuid().ToString();
LogContext.PushProperty("CorrelationId",correlationId);
await _next(context);
}
}
Logging User Information
Applications often need user-related information for auditing and security analysis.
using(LogContext.PushProperty("UserId",userId))
{
_logger.LogInformation("User performed operation");
}
Sensitive information such as passwords and security tokens should never be written into logs.
Production Logging Architecture
A professional production environment usually separates log collection, processing, storage, and visualization.
ASP.NET Core Application -> Serilog -> Log Collection System -> Centralized Storage -> Dashboard / Monitoring
Recommended Production Logging Strategy
- Use structured logging instead of plain text
- Store logs centrally
- Include correlation identifiers
- Capture exceptions with full details
- Configure appropriate log levels
- Monitor critical application failures
Performance Considerations
Poorly configured logging can affect application performance. Enterprise applications should follow efficient logging practices.
Recommended Practices
- Avoid excessive Debug logs in production
- Use asynchronous sinks where required
- Avoid logging large objects unnecessarily
- Filter unnecessary framework logs
- Rotate and archive old logs
Security Considerations for Logging
Logs often contain sensitive operational information, so they should be handled carefully.
Never Log
- Passwords
- Authentication tokens
- Credit card information
- Private user data
- Encryption keys
Serilog Logging in Microservices
Serilog is especially useful in microservice environments where multiple services generate large amounts of operational data.
Using Serilog Through Dependency Injection
ASP.NET Core provides built-in dependency injection support. Serilog integrates with this system by replacing the default logging provider while keeping the standard ILogger interface.
Service Class Logging Example
public class PaymentService
{
private readonly ILogger<PaymentService> _logger;
public PaymentService(ILogger<PaymentService> logger)
{
_logger = logger;
}
public void ProcessPayment()
{
_logger.LogInformation("Payment processing started");
try
{
// Payment logic
}
catch(Exception ex)
{
_logger.LogError(ex,"Payment processing failed");
}
}
}
Using ILogger allows developers to write clean code without directly depending on Serilog classes.
Logging Background Services
ASP.NET Core applications often contain background workers for scheduled tasks, queue processing, and automation.
Background Service Logging Example
public class EmailWorker: BackgroundService
{
private readonly ILogger<EmailWorker> _logger;
public EmailWorker(ILogger<EmailWorker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Email worker started");
while(!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Processing email queue");
await Task.Delay(5000);
}
}
}
Common Serilog Mistakes to Avoid
- Logging sensitive information
- Creating too many unnecessary log entries
- Ignoring structured logging features
- Keeping unlimited log files
- Using incorrect log levels
- Not monitoring production logs
- Writing custom logging solutions unnecessarily
Serilog Best Practices Checklist
| Practice | Recommendation |
|---|---|
| Log Format | Use structured logging |
| Storage | Use centralized log management |
| Errors | Always capture exception details |
| Security | Avoid sensitive information |
| Performance | Configure proper filtering |
| Production | Use appropriate log levels |
Enterprise Logging Architecture Example
A mature enterprise system usually follows a centralized logging architecture where applications send structured events to a monitoring platform.
Advantages of Serilog in Enterprise Applications
- Improved application monitoring
- Faster troubleshooting
- Better production visibility
- Searchable structured events
- Integration with monitoring platforms
- Flexible storage options
- Better debugging experience
Frequently Asked Questions
What is Serilog used for in ASP.NET Core?
Serilog is used for capturing application logs in a structured format. It helps developers monitor applications, troubleshoot issues, and analyze system behavior.
Is Serilog better than built-in ASP.NET Core logging?
ASP.NET Core logging provides a useful abstraction, while Serilog adds advanced features such as structured logging, multiple sinks, enrichers, and centralized log management.
Can Serilog store logs in a database?
Yes. Serilog supports database logging using different sinks including SQL Server and other storage systems.
What is structured logging?
Structured logging stores log information as properties and values instead of only plain text messages. This makes searching and analyzing logs easier.
Should Debug logs be enabled in production?
Usually, production environments use Information level or higher to reduce noise and maintain application performance. Debug logging may be enabled temporarily for troubleshooting.
Can Serilog be used with microservices?
Yes. Serilog is commonly used in microservice architectures because it supports structured events, centralized logging, and distributed request tracking.
Conclusion
Serilog provides a powerful and flexible logging solution for modern ASP.NET Core applications. Its structured logging approach helps development teams understand application behavior, diagnose issues quickly, and improve system reliability.
By combining Serilog with proper configuration, centralized storage, correlation identifiers, and security practices, organizations can build a professional logging strategy for enterprise applications.
For ASP.NET Core projects of any size, effective logging is not only about recording errors. It is about creating visibility into the complete application lifecycle.