Setting up Serilog in ASP.NET Core -Detailed Guide

Table of contents

What is SeriLog
What is Sink in serilog
What are the enrich in serilog?
How to configure Serilog in .NET Core
How to add enricher in Serilog?
How to add sink in Serilog?
Message template
How to override the log level

This blog will show you how to configure Serilog in the asp.net core application. Logging is significant in any application; by using logging, we can easily troubleshoot the production issue. ASP.NET core already provided the logging features, but in this blog, we will discuss Serilog which is a very popular logging framework for the .net core application

By the end of this tutorial you will be learn the following things

  • What is SeriLog and how to configure in .net core application
  • How to use Serilog enrichers like serilog enrich for machine name
  • How to configure Sqlite in Serilog
  • How to use serilog message template

What is SeriLog

SeriLog is a structured logging library for a .NET core application. It is straightforward to integrate and provide a lot of output (Sink) format like Console,File And databases like SQLLite.

What is Sink in serilog?

Sink in serilog means where serilog output the Log like standard output, file, or somewhere else. Serilog out of the box provides the following Sink.

  • Console
  • File
    The syntax for using Sink is as follows
Log.Logger = new LoggerConfiguration()
	 .WriteTo.Console()
	 .WriteTo.File(@"c:\\temp\\log.txt")
    .CreateLogger();

What are the enrich in serilog?

Serilog Enrich allows you to add new properties other than the ones originating from the message template. An example of enrichers is logging. ThreadId,ProcessId, machine name` etc. You can add them with the following syntax

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

How to configure Serilog in .NET Core

$ads={1}

Integrating serilog in the .net core application is very straightforward.

STEP-1

Create an application using .net core CLI and then install the serilog library from the NuGet

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

STEP-2

Open Program.cs and add the following code snippet

 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();
		// Serilog configuration
        public static void ConfigureSerilog()
        {
            Log.Logger = new LoggerConfiguration()
                .WriteTo.Console()
                .CreateLogger();
        }
    }

In the above code snippet, the serilog configuration is inside the ConfigureSerilog method. Let’s break down the technique.

  • The LoggerConfiguration the class provides a fluent interface for building a logging pipeline
  • WriteTo.Console() adds the console sink to the pipeline, which will log the events to standard output, which is the console in our case
  • CreateLogger() assembles everything and returns a Logger object, which implements ILogger
  • Now serilog pipeline is integrated with the .NET Core, and you can use Log.Information() and Log.Error() emit events through the logger

How to add enricher in Serilog?

To add an enricher in serilog, first, you have to install the enricher from the NuGet package and then add the enricher in the pipeline, as shown below

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

In the above code snippet, I am adding two enrichers which will add ThreadId and MachineName to serilog log events

How to add a sink in Serilog?

When you install the Serilog library in your application Serilog by default, install two sinks named Console and File. But if you want to configure any other sink like SQLite sink, first you have to install the Sink from the NuGet, and then you can use the Sink as shown below.

dotnet add package Serilog.Sinks.SQLite

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

Add WriteTo.SQLite and pass the database name. Now your log message will be written to Console, File, and SQLite database.
code guru

Message template

Serilog provides a simple DSL for customizing the log message. Serilog Message templates are a superset of standard .NET format strings, so any format string acceptable will also be correctly processed by Serilog.

  • Property names are written between { and } brackets
  • Property names must be valid C# identifiers, for example FooBar, but not Foo.Bar or Foo-Bar
  • Brackets can be escaped by doubling them, e.g. {{ will be rendered as {
  • Property names should use PascalCase for consistency with other code and libraries from the Serilog ecosystem.
    Let’s consider you want to print the ThreadIs and MachineName in the log message then you can pass the message template as shown below
 .WriteTo.File("c:\\temp\\log.txt", outputTemplate: "{Timestamp:yyyy-mm-dd} {MachineName} {ThreadId} {Message} {Exception:1} {NewLine}"

OUTPUT

codeguru

How to override the log level

You can override the log level events from the code as well as from the config file.


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

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

Post a Comment (0)
Previous Post Next Post