35

I've created a .NET Core 3.1 project using a Host, the IoC container with IServiceCollection and implemented logging allover the place using the ILogger<T> interface from Microsoft.Extensions.Logging. I now need to implement more advanced logging and decided to use Serilog.

I assumed that it would be a breeze to switch from .NET built-in loggers to Serilog. But to my surprise, Serilog is using it's own ILogger interface - bummer! So now I needed to update ALL places to use Serilog ILogger, or to implement Serilog with a .NET Core ILogger<T> interface.

My question is - is it really not possible to use Serilog with the ILogger interface in Microsoft.Extensions.Logging? Would be so much smarter!

iliketocode
  • 6,978
  • 5
  • 46
  • 60
morteng
  • 689
  • 2
  • 7
  • 18
  • 1
    "_I kinda assumed that it would be a breeze to switch from .NET built-in loggers to Serilog_" - It is... Just use [Serilog's provider for Microsoft.Extensions.Logging](https://github.com/serilog/serilog-extensions-logging) – C. Augusto Proiete May 01 '20 at 15:17
  • 1
    Also, you might be interested in this other question: "[Serilog DI in ASP.NET Core, which ILogger interface to inject?](https://stackoverflow.com/q/61411759/211672)" – C. Augusto Proiete May 01 '20 at 15:20

2 Answers2

39

In the Serilog.Extensions.Logging assembly there is a extension method on IloggingBuilder called AddSerilog (it's in the Serilog namespace) that will allow you to use Serilog for logging. For example:

.NET Core 2.2 and earlier (using WebHost):

WebHost.CreateDefaultBuilder(args)
    .ConfigureLogging(logging =>
    {
        logging.ClearProviders();
        logging.AddSerilog();
    });

.NET Core 3.1 and later (using generic Host for either web or console apps):

Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>()})
    .UseSerilog();

Now the ILogger and ILogger<> implementation will call into Serilog.

Thiago Silva
  • 8,506
  • 2
  • 29
  • 43
Sean
  • 58,802
  • 11
  • 90
  • 132
  • 13
    And if you're using Generic Host, there is Serilog.Extensions.Hosting package which has a UseSerilog method to configure the Serilog setup – pinkfloydx33 May 01 '20 at 14:31
5

For .NET 6 and later

using Serilog;

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog((ctx, lc) => lc
    .WriteTo.Console()
    .ReadFrom.Configuration(ctx.Configuration));

Reference: Here

Shuvo Amin
  • 123
  • 2
  • 8
  • You'll need to run `dotnet add package Serilog.AspNetCore` for ASP.NET Core or `Serilog.Extensions.Hosting` before referencing those lines. – Exegesis Jun 02 '22 at 16:00