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
builder.Logging.ClearProviders();
// Serilog configuration		
var logger = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateLogger();
// Register Serilog
builder.Logging.AddSerilog(logger);
		
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");
	
app.Run();

That's it.

Recommended content

Comments

  • 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); });


  • Pete

    November 06, 2026

    We absolutely love your blog and find the majority of your post's tto be just what I'm looking for. Doess one offer guest writers tto write content for you? I wouldn't mind creating a post or elaboraing onn mowt of the subjects yoou write with rgards too here. Again, awesome weeb sitye (<a href="https://hot.xvideosfap.cc/">https://hot.xvideosfap.cc/</a>)! xnxx


Leave your comment