DotNet By Ajay — New: ES2025 cheat-sheet is live!

June 17, 2025

How to Implement Serilog in ASP.NET Core (.NET 8/9) – Step-by-Step Logging Guide

Implement Serilog in ASP.NET Core


Published on: June 17, 2025
Category: Dev Tutorials / Logging
Tags: .NET Core, ASP.NET Core, Serilog, Structured Logging, Dev Tutorial



๐Ÿ” Why Logging Matters

Logging is crucial for debugging, monitoring, and maintaining applications. In modern .NET development, Serilog has emerged as a powerful logging library offering structured log data.



⚙️ What is Serilog?

Serilog is a diagnostic logging library for .NET applications. It supports structured logging and allows you to route logs to multiple outputs (called sinks) such as:

  • Console
  • File
  • Seq
  • Elasticsearch


๐Ÿš€ Step-by-Step Setup in ASP.NET Core

1️⃣ Install NuGet Packages


Install-Package Serilog.AspNetCore
Install-Package Serilog.Sinks.File
  

2️⃣ Program.cs Configuration (.NET 6+)


using Serilog;

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.File("Logs/app-log.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog();

var app = builder.Build();
app.Run();
  

3️⃣ Logging in Controllers/Services


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

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

    public IActionResult Index()
    {
        _logger.LogInformation("Visited Home Page");
        return View();
    }
}
  


๐Ÿ’ก Best Practices

  • Use rolling logs to prevent large file sizes
  • Store logs outside of the web root
  • Use structured logs with properties for easier filtering

๐Ÿงช Output Sample


[2025-06-17 10:45:22 INF] Visited Home Page
  


๐Ÿ“Œ Summary

Serilog offers a flexible, powerful way to manage logging in .NET applications. It simplifies diagnostics and helps you trace issues efficiently with minimal performance impact.



No comments:

Post a Comment