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
{
}
}
Microsoft ILogger interface
Enough with the words - show me the code
In the Program.cs
add 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
Program implementation with Serilog
With the changes made until here we can inject the ILogger
interface 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();
Them we have added Serilog
as Logging Provider in native logging system.
builder.Host.UseSerilog();
Output
Again - All done here. If you like it Subscribe for more.
Originally posted at https://rmauro.dev/setup-serilog-in-net6-as-logging-provider/
Top comments (2)
Nice one @rmaurodev!!
You could expand this to show how you can use
appsettings.json
to configure the logger too. Makes it an even easier setup and then in a container it's overridable by environment variables per deployment environment. I have a project with the local dev to console and docker to Seq in a container.Program.cs
appsettings.json
Nice. Thanks for the feedback.
Wait for the next one on this subject. I'll include that.