Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Serilog with Microsoft.Extensions.Logging.ILogger

Tags:

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!

like image 256
morteng Avatar asked May 01 '20 14:05

morteng


People also ask

What is the use of Microsoft extensions logging?

Extensions. Logging provided by ASP.NET Core. This provides an ILogger interface that allows the provider of your choice to be used while minimizing the impact to existing code.

What is the difference between ILogger and ILoggerFactory?

ILogger: is responsible to write a log message of a given Log Level. ILoggerFactory: you can register one or more ILoggerProvider s with the factory, which in turn uses all of them to create an instance of ILogger . ILoggerFactory holds a collection of ILoggerProviders .

Is Serilog logger thread safe?

Yes, ILogger s in Serilog are always safe to use concurrently from multiple threads.


1 Answers

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.

like image 83
Sean Avatar answered Sep 17 '22 07:09

Sean