How to configure Serilog in .Net 6

How to configure Serilog in .Net 6

Serilog Configure Process

Table of contents

Installation

First, you will have to install Serilog to your project from your Nuget Package

SerilogNuget.png

Great, let's add the Using Serilog namespace in your program.cs file

SerilogNamespace.png

Configuration

After that we will configure the serilog code in the program.cs file that will be fetching it's method from appsettings.json file.

Paste this following code in your program.cs file

//############ Serilog Service Injection #################
var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .Build();

Note: This method fetches serilog method from appsettings.Json file.

Then let's add the serilog method into appsettings.Json file

  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "Default": "Error",
    "MinimumLevel": "Warning",
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": { "path": "Log/log.log" }
      }
    ]
  }

Above Explained:

SerilogUsingappsettings.png

  1. The "Serilog" connects with the namespace
  2. The "Using" gets the neccessary package from the Serilog.AspNetCore nuget package

Default-Minimumlevel.png

  1. The "Default" logs error messages
  2. The "MinimumLevel" logs only Warning message to the log file

Note: the default serve as an additional field for specifying other log message you would like to include.

SerilogWriteTo.png

  1. The "WriteTo" tells where to save the log messages
  2. The "Name" tells the project to also allow the log message to be displayed at the console page
  3. While the other "Name": "File" tells the project to create a file instance folder
  4. Lastly, the "Args": {"path": "Log/Log.log"} tells the project to create a Folder Log and inside the folder a file log.log

Finally let's finish the configuration process in our program.cs file

FinalConfiguration.png

Let add this method in our program.cs file:

Log.Logger = new LoggerConfiguration() // Creates a logger configuration as Serilog
    .ReadFrom.Configuration(configuration) //This will readFrom the configured method from appsettings.Json file
    .CreateBootstrapLogger(); //This will add bootstrap color to the log message at the console.

builder.Host.UseSerilog();//This will inject the whole serilog configuration method into your project

Thank you.

Having any issue configuring? Kindly drop your comment...

Did you find this article valuable?

Support Idowu's blog by becoming a sponsor. Any amount is appreciated!