Logging Made Easy: Using Serilog in ASP.NET Core Web API

Introduction

This blog post will guide you through the process of configuring Serilog in an ASP.NET Core application. Logging is an essential aspect of any application, as it allows us to troubleshoot issues in production environments effectively. While ASP.NET Core already provides logging features, we will explore Serilog, a popular logging framework for .NET Core applications, in this blog.

By the end of this tutorial, you will learn:

  • What Serilog is and how to configure it in a .NET Core application
  • How to use Serilog enrichers, such as enriching logs with machine name
  • How to configure Serilog with SQLite
  • How to utilize Serilog’s message template for log formatting
  • How to override the log level for different log events

What is Serilog?

Serilog is a structured logging library for .NET Core applications. It offers easy integration and supports various output formats, referred to as sinks. These sinks include Console, File, and even databases like SQLite.

What is a Sink in Serilog?

A sink in Serilog determines where the log events will be outputted. It could be the console, a file, or any other destination. Serilog provides built-in sinks such as Console and File. Configuring a sink is simple:

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.File(@"c:\\temp\\log.txt")
    .CreateLogger();

In the above example, we configure Serilog to output log events to the console and a file.

What are Enrichers in Serilog?

Serilog enrichers allow you to add additional properties to the log events, beyond those present in the message template. These properties can provide valuable contextual information, such as ThreadId, ProcessId, and MachineName. Enrichers can be added to the logger configuration as follows:

Log.Logger = new LoggerConfiguration()
    .Enrich.WithThreadId()
    .Enrich.WithMachineName()
    .CreateLogger();

In the above snippet, we add two enrichers that include ThreadId and MachineName to the log events.

How to Configure Serilog in .NET Core

Configuring Serilog in a .NET Core application is straightforward. Let’s go through the steps:

Step 1: Create a new application using the .NET Core CLI and install the Serilog.AspNetCore package from NuGet:

dotnet new webapp loggerdemo
dotnet restore
dotnet add package Serilog.AspNetCore

Step 2: Open the Program.cs file and add the following code:

public class Program
{
    public static void Main(string[] args)
    {
        ConfigureSerilog();

        Log.Information("Starting the application");

        try
        {
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
        finally
        {
            Log.Information("Application closed");
            Log.CloseAndFlush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); })
            .UseSerilog();

    public static void ConfigureSerilog()
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .CreateLogger();
    }
}

In the above code snippet, the ConfigureSerilog method is responsible for setting up the Serilog configuration. We use the LoggerConfiguration class to build the logging pipeline, and in this case, we configure it to write log events to the console.

How to Add Enrichers in Serilog

To add enrichers in Serilog, you need to install the appropriate NuGet package and include them in the logger configuration. For example:

Log.Logger = new LoggerConfiguration()
    .Enrich.WithThreadId()
    .Enrich.WithMachineName()
    .CreateLogger();

In the above code snippet, we add two enrichers: WithThreadId and WithMachineName, which add the ThreadId and MachineName properties to the log events.

How to Add Sinks in Serilog

Serilog provides built-in sinks such as Console and File. However, you can install additional sinks from NuGet packages and configure them in your Serilog pipeline. For example, to use the SQLite sink, follow these steps:

Step 1: Install the Serilog.Sinks.SQLite package from NuGet:

dotnet add package Serilog.Sinks.SQLite

Step 2: Configure the SQLite sink in your Serilog pipeline:

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.SQLite(@"c:\\temp\\log.db")
    .WriteTo.File(@"c:\\temp\\log.txt")
    .CreateLogger();

In the above code snippet, we add the WriteTo.SQLite configuration to specify the SQLite database where the log messages will be stored. You can combine multiple sinks in your pipeline, and log events will be sent to all specified destinations.

Message Template in Serilog

Serilog uses message templates to format log messages. These templates are a superset of standard .NET format strings. Inside the templates, property names are enclosed in {} brackets. You can include properties like Timestamp, MachineName, ThreadId, and Message in the log output. Here’s an example:

.WriteTo.File("c:\\temp\\log.txt", outputTemplate: "{Timestamp:yyyy-MM-dd} {MachineName} {ThreadId} {Message} {Exception:1} {NewLine}")

code guru

In the above code snippet, the output template specifies the desired log message format. The properties inside the brackets will be replaced with their corresponding values in the actual log events.

How to Override the Log Level

You can override the log level for different events in Serilog, both programmatically and through configuration. To set the minimum log level globally, use the MinimumLevel method. For example:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
    .CreateLogger();

In the above code snippet, the minimum log level is set to Debug for all events. Additionally, for events coming from the “Microsoft” namespace, the minimum level is overridden to Information. You can adjust the log levels based on your application’s requirements and desired verbosity.

By following the steps and examples provided in this blog post, you can easily configure Serilog in your ASP.NET Core application, add enrichers and sinks, customize log message templates, and override log levels as needed. Serilog’s flexibility and powerful features make it a popular choice for logging in .NET Core applications.

إرسال تعليق

Please do not post any spam link in the comment box😊

أحدث أقدم

Blog ads

CodeGuru