Serilog Integration in ASP.NET Core

What is Serilog?

Serilog is a popular logging library for .NET applications. It provides structured logging, which allows logs to be written in a format that is easy to read, search, and analyze.

  • Structured Logging: Log data in key-value pairs for better organization.
  • Extensible: Support for various sinks like console, file, database, and cloud services.
  • Powerful Features: Includes enrichers, filters, and formats for customized logging.

How to Integrate Serilog in ASP.NET Core

Follow these steps to integrate Serilog into your ASP.NET Core application:

1. Install Required NuGet Packages

Install the necessary Serilog packages using the .NET CLI or NuGet Package Manager.


dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Settings.Configuration
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.File

                

These packages include the core library and sinks for writing logs to the console and a file.

2. Configure Serilog

Set up Serilog in your Program.cs file.


// Program.cs
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Configure Serilog
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .WriteTo.Console()
    .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

builder.Host.UseSerilog();

var app = builder.Build();
app.MapGet("/", () => "Hello, Serilog!");

app.Run();

                

This configuration reads settings from the app configuration and writes logs to the console and a rolling log file.

3. Add Configuration in appsettings.json

Add Serilog settings in the appsettings.json file for centralized configuration.


{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      { "Name": "File", "Args": { "path": "logs/log-.txt", "rollingInterval": "Day" } }
    ]
  }
}

                

This configuration sets the logging level and defines sinks for the console and file.

4. Use Logging in Application

Inject ILogger<T> to log messages in your application.


// Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;

public class HomeController : ControllerBase
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    [HttpGet("/")]
    public IActionResult Index()
    {
        _logger.LogInformation("Hello from Serilog!");
        return Ok("Check the logs for the message.");
    }
}

                

Use _logger to log messages with different severity levels, such as Information, Warning, and Error.


Why Use Serilog?

  • Improved Debugging: Structured logs make it easier to identify and resolve issues.
  • Flexible Output: Log to multiple destinations like files, databases, or cloud services.
  • Performance: Highly efficient and lightweight.