Set up Serilog in .NET 6 as logging provider

Ricardo - Jul 5 '22 - - Dev Community

Serilog is a robust API for logging with many configurations and sinks (outputs) and it is straightforward to get started in any .NET version.

Originally posted at https://rmauro.dev/setup-serilog-in-net6-as-logging-provider/

With .NET 6 the way we used to configure Serilog as a logging provider in .NET 5 it is gonne (no more, no way sir, no no, good bye), it's no longer there.

Bootstraping a .NET 6 application is difference from older version but still pretty easy.

Like many other libraries for .NET, Serilog provides diagnostic logging to files, the console, and elsewhere. It is easy to set up, has a clean API, and is portable between recent .NET platforms. Unlike other logging libraries, Serilog is built with powerful structured event data in mind.

Words from https://serilog.net/

Let's set up Serilog as Logging Provider in the native logging system in .NET so you can use the Microsoft ILogger interface.

namespace Microsoft.Extensions.Logging
{
    public interface ILogger<out TCategoryName> : ILogger
    {
    }
}
Enter fullscreen mode Exit fullscreen mode

Microsoft ILogger interface

Enough with the words - show me the code

In the Program.csadd these code changes.

using Serilog;

//create the logger and setup your sinks, filters and properties
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateBootstrapLogger();

var builder = WebApplication.CreateBuilder();
//after create the builder - UseSerilog

builder.Host.UseSerilog();

//redacted code
Enter fullscreen mode Exit fullscreen mode

Program implementation with Serilog

With the changes made until here we can inject the ILoggerinterface and use Serilog as a log provider.

Breaf Explanation

Set up the global variable Serilog.Logger with the sink Console and bootstrap a logger.

//create the logger and setup your sinks, filters and properties
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateBootstrapLogger();
Enter fullscreen mode Exit fullscreen mode

Them we have added Serilog as Logging Provider in native logging system.

builder.Host.UseSerilog();
Enter fullscreen mode Exit fullscreen mode

Output

Set up Serilog in .NET 6 as logging provider
Serilog Output Sample

Again - All done here. If you like it Subscribe for more.

Originally posted at https://rmauro.dev/setup-serilog-in-net6-as-logging-provider/

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .