πŸ“Š Supercharge Your ASP.NET Core Logging with Serilog

 

Logging is your best friend when debugging, monitoring, or auditing your application. While .NET has built-in logging, it lacks the flexibility and structure needed for scalable, production-grade applications. That’s where Serilog comes in.

In this blog post, you'll learn what Serilog is, why it's a game-changer, and how to set it up quickly in your .NET project.


πŸ” What Is Serilog?

Serilog is a structured logging library for .NET that allows you to write logs to:

  • Console
  • Files
  • Databases
  • Seq
  • Elasticsearch
  • Application Insights
  • And many more sinks...

Unlike plain-text logs, Serilog writes structured logs (e.g., JSON), making them easier to query, filter, and visualize in tools like Kibana, Seq, or Datadog.


✅ Why Use Serilog?

Feature

Benefit

Structured logging

Log data in key-value pairs (great for filtering)

Rich sinks ecosystem

Log to almost any service or storage

Asynchronous logging

Non-blocking performance

Flexible config

Configure via code or appsettings.json

Easy integration

Seamless setup in ASP.NET Core


πŸš€ Getting Started with Serilog in ASP.NET Core


Step 1️⃣: Install the Required NuGet Packages

 

dotnet add package Serilog.AspNetCore

dotnet add package Serilog.Settings.Configuration

dotnet add package Serilog.Sinks.File

dotnet add package Serilog.Sinks.Console


Step 2️⃣: Configure Serilog in Program.cs

csharp

 

using Serilog;

 

var builder = WebApplication.CreateBuilder(args);

 

// Configure Serilog

Log.Logger = new LoggerConfiguration()

    .ReadFrom.Configuration(builder.Configuration)

    .Enrich.FromLogContext()

    .WriteTo.Console()

    .WriteTo.File("Logs/app-.log", rollingInterval: RollingInterval.Day)

    .CreateLogger();

 

// Replace default logging with Serilog

builder.Host.UseSerilog();

 

builder.Services.AddControllers();

 

var app = builder.Build();

app.UseAuthorization();

app.MapControllers();

app.Run();


Step 3️⃣: Add Settings in appsettings.json

json

 

"Serilog": {

  "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],

  "MinimumLevel": {

    "Default": "Information",

    "Override": {

      "Microsoft": "Warning",

      "System": "Warning"

    }

  },

  "WriteTo": [

    {

      "Name": "Console"

    },

    {

      "Name": "File",

      "Args": {

        "path": "Logs/app-.log",

        "rollingInterval": "Day"

      }

    }

  ],

  "Enrich": [ "FromLogContext" ]

}


Step 4️⃣: Use Serilog in Your App

csharp

 

public class HomeController : ControllerBase

{

    private readonly ILogger<HomeController> _logger;

 

    public HomeController(ILogger<HomeController> logger)

    {

        _logger = logger;

    }

 

    [HttpGet("test-log")]

    public IActionResult Test()

    {

        _logger.LogInformation("This is an info log from Serilog.");

        _logger.LogWarning("This is a warning.");

        _logger.LogError("Something went wrong at {Time}", DateTime.UtcNow);

        return Ok("Logged successfully.");

    }

}


🧠 Advanced Features

πŸ”Ή Log Enrichment

Add custom data (e.g., user ID, request ID) automatically to every log:

csharp

CopyEdit

.Enrich.WithProperty("Application", "MyAwesomeApp")

.Enrich.FromLogContext()

πŸ”Ή Filters

Ignore noisy logs:

csharp

.Filter.ByExcluding(log => log.Level == LogEventLevel.Debug)

πŸ”Ή Async Logging

Prevent log writing from blocking your app:

csharp

CopyEdit

.WriteTo.Async(a => a.File("Logs/app.log"))


πŸ“¦ Useful Sinks

Sink

Description

File

Logs to rolling log files

Console

Debug and local environments

Seq

Great for local structured viewing

Elasticsearch

Searchable logs via Kibana

MSSQL / PostgreSQL

Persist logs to DB tables


⚠️ Best Practices

  • Log structured data (not just strings)
  • Avoid logging sensitive info (e.g., passwords, tokens)
  • Use appsettings-based config for flexibility
  • Enable rolling files to avoid huge logs
  • Add Request ID correlation for tracing API calls

πŸ“ˆ Summary

Serilog gives you professional-grade logging with minimal setup:

✅ Structured, queryable logs
✅ Multiple output targets (sinks)
✅ Easy integration with ASP.NET Core
✅ Great for production diagnostics and observability

 

Comments

Popular posts from this blog

Scrutor the built-in Dependency Injection (DI)

🌐 CORS in .NET Explained: Solving the Cross-Origin Problem Like a Pro

πŸ§… Understanding the Onion Architecture: A Clean Approach to Building Scalable Applications

πŸ”Œ Extension Methods in C#: Power Up Your Code Without Modifying It

Understanding Dependency Injection: A Modern Guide for Developers

πŸ” JWT (JSON Web Token) Explained: Secure Your APIs the Modern Way

πŸ›‘️ SIEM Logs Explained: How to Build Secure and Auditable .NET Apps

Ensuring Data Integrity: The Backbone of Reliable Systems

πŸ—‚️ DROP vs DELETE vs TRUNCATE in SQL: What’s the Difference?

πŸ”— SQL JOINs Explained: Mastering Table Relationships