How to configure Serilog in .Net 6
Table of contents
Installation
First, you will have to install Serilog to your project from your Nuget Package
Great, let's add the Using Serilog namespace in your program.cs file
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:
- The "Serilog" connects with the namespace
- The "Using" gets the neccessary package from the Serilog.AspNetCore nuget package
- The "Default" logs error messages
- 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.
- The "WriteTo" tells where to save the log messages
- The "Name" tells the project to also allow the log message to be displayed at the console page
- While the other "Name": "File" tells the project to create a file instance folder
- 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
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...
Subscribe to my newsletter
Read articles from Idowu Adekale directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Idowu Adekale
Idowu Adekale
A software Engineer, adept at using C#, JavaScript, Asp.net Core, Html, CSS