Using Serilog for Logging in .NET


Last Updated: 2/20/2024

Serilog

  • 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.
  • Serilog is built with powerful structured event data in mind.
  • Structured logging is a modern approach where logging events are treated as structured data rather than text
  • NLog
  • Log4Net
  • Serilog

Console Sample

  • Create console Project
  • Add packages
Serilog
Serilog.Sinks.Console
Serilog.Sinks.File
  • Add the following code in the start of program.cs
Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateLogger();
  • Messages are logged to console

ASP.NET Sample

  • Create new asp.net core project
  • Install package
Install-Package Serilog.AspNetCore
  • Add the following code in the start of program.cs
Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateLogger();
  • Messages are logged to console

Default Logger

  • Configure serilog as the default logger
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((ctx, lc) => lc.WriteTo.Console());

Logging with Json Format - Structured Logging

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console(new JsonFormatter())
    .CreateLogger();

Logging to File

  • Install Package
Install-Package Serilog.Sinks.File
  • Configure file logger
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console(new JsonFormatter())
    .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

Logging to Db

  • Install Package
Install-Package Serilog.Sinks.MSSqlServer
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console(new JsonFormatter())
    .WriteTo.File(new JsonFormatter(), "log.txt")
    .WriteTo.MSSqlServer("Data Source=localhost;Initial Catalog=Sample;Integrated Security=SSPI",
                         new MSSqlServerSinkOptions
                         {
                             TableName = "Logs",
                             SchemaName = "dbo",
                             AutoCreateSqlTable = true
                         })
    .CreateLogger();

Logging Levels

  • Levels from priority low to high
    • Verbose
    • Debug
    • Info
    • Warning
    • Error

Configure Logging Level

Configure Minimum logging level in Console

Log.Logger = new LoggerConfiguration().MinimumLevel.Warning().WriteTo.Console().CreateLogger();

Configure Minimum logging level in ASP.NET Core

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console(new JsonFormatter())
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
    .CreateLogger();
  • Configure middleware
app.UseSerilogRequestLogging();

References: