Use Serilog with Minimal API in .NET 6

November 19, 2021

If you want to replace the standard logging with Serilog in a Minimal API you have to do just a couple of steps.

At first, you have to add a reference to a NuGet package Serilog.AspNetCore. You can do it in Visual Studio or in the command line using dotnet CLI tool:

dotnet add package Serilog.AspNetCore

At second, you need to register Serilog as your logger in Program.cs:

var builder = WebApplication.CreateBuilder(args);

// remove default logging providers
// Serilog configuration		
var logger = new LoggerConfiguration()
// Register Serilog
var app = builder.Build();

// How to use logging inside your method
app.MapGet("/", (ILoggerFactory loggerFactory) => {
    var logger = loggerFactory.CreateLogger("index");
    logger.LogInformation("index called");
    return "Hello world";

// How to use logging in Program.cs file		
app.Logger.LogInformation("The application started");

That's it.

Recommended content


  • kiquenet

    September 29, 2022

    How-to inject ILoggerFactory in BLL classes? app.MapGet("/" => { return new Facade().GetMessage("Hello world"); }); internal class Facade internal string GetMessage(string msg) => new BLL().Get(msg);

  • Andrew

    October 05, 2022

    2 kiquenet There are multiple options. However, the best one is to inject ILogger<T> via constructor, like: internal class Facade { private readonly ILogger<Facade> _logger; public Facade(ILogger<Facade> logger) { _logger = logger } internal string GetMessage(string msg) => new BLL().Get(msg); } Another option pass it to GetMessage method like: app.MapGet("/", (ILoggerFactory loggerFactory) => { return new Facade().GetMessage("Hello world", loggerFactory); });

Leave your comment