Implementing Logging in ASP.NET Core MVC using Serilog

Introduction

Logging serves as a crucial component of application development, functioning as a black box that records events, providing insight into what occurred when it took place and the reasons behind various actions. In this blog, I will guide you through the process of integrating Serilog, a robust structured logging library, into an ASP.NET Core MVC application. We will explore the necessary steps, starting from the installation of Serilog to its configuration for logging into both files and the console. Additionally, practical examples from a real-world project will be included to illustrate these concepts. Whether you are new to logging or seeking to enhance your diagnostic capabilities, this guide offers a comprehensive approach to achieving professional-grade logging.

What is Serilog?

Serilog is a clean, easy-to-setup logging library for .NET. It supports:

  • Structured logging
  • Multiple sinks (e.g., Console, File, Seq, etc.)
  • Enrichment for contextual logs
  • Rolling log files
  • Helpful for Debugging

Step 1. Install Serilog Packages

Open the Package Manager Console in Visual Studio and run:

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

Step 2. Configure Serilog in Program.cs

Open your Program.cs file and configure Serilog like this:

using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Configure Serilog
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .WriteTo.Console()
    .WriteTo.File("Logs/log.txt", rollingInterval: RollingInterval.Day)
    .Enrich.FromLogContext()
    .CreateLogger();

builder.Host.UseSerilog();

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Log application startup
Log.Information("Application is starting...");

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

try
{
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Application terminated unexpectedly.");
}
finally
{
    Log.CloseAndFlush();
}

Step 3. Use Serilog in Your Controllers

You can inject ILogger<T> into your controllers like this:

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

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

    public IActionResult Index()
    {
        _logger.LogInformation("Fetching all tasks...");
        return View();
    }

    public IActionResult Create()
    {
        _logger.LogInformation("Rendering Create Task view.");
        return View();
    }

    [HttpPost]
    public IActionResult Create(TaskModel model)
    {
        if (ModelState.IsValid)
        {
            _logger.LogInformation("Task created: {@Task}", model);
            // Save to DB (not shown)
            return RedirectToAction("Index");
        }

        _logger.LogWarning("Invalid task model submitted.");
        return View(model);
    }
}

// Use structured logging with {@Object} to log the full object for better diagnostics.

Clean Up

Always remember to flush logs using:

Log.CloseAndFlush();

This ensures all logs are written before your app shuts down.

Sample Log Output

Here's what your log.txt might look like:

[Information] Fetching all tasks...

[Information] Task created: { Title: "Write Blog", DueDate: "2025-04-15", IsCompleted: false }

[Warning] Invalid task model submitted.

Conclusion

Integrating Serilog into an ASP.NET Core MVC application is a straightforward and effective process. By implementing a few lines of configuration, developers can achieve comprehensive control over the logging mechanism, determining precisely how and where logs are recorded. This method is beneficial not only in the development phase but also plays a crucial role in production environments, facilitating effective monitoring and debugging of applications. This approach not only helps during development but also proves invaluable in production for monitoring and debugging.

Ebook Download
View all
Learn
View all