Logging is one of the fundamental aspects of our development because it helps us figure out our problems quickly.
We need to log our requests and response and then we can use them to identify the issues.
We have two famous logging libraries available in .NET
Serilog
Serilog specifically shines in the structured logging area, one could ask what structured logging is:
Well, structured logging says we follow a same structure to save our logs throughout the application.
Let’s set up Serilog.
Installing Serilog
The next step to configure is calling UseSerilog
method over our host builder and configure configurations.
I prefer to keep this process in a different extension method like this :
Now we can call this in Program.cs :
Understanding the Configurations
Configurations are a way to tell Serilog the following things :
Where should our logs be displayed console or file?
What should be the rolling interval?
Which additional details should be added in logs e.g. machine name, thread ID, etc
What should be the minimum level of our logs e.g. Warning, Error, or Information?
There are two ways to configure this :
Using app settings
Using code
How to set up configurations via app settings?
We have to add a section with the name Serilog in app settings like this :
This is all that we need to do, wondering how this would be read. This part is doing that magic :
I prefer setting up configuration via app setting because it is much more flexible than the second approach.
How to set up configurations via code?
Let’s set up the configuration in a file first, so we can call that later on :
Let’s call it in our Program.cs
now
How to use the logger in the controller or any other class?
Just inject ILogger with your desired class like this and use it :
If you are using Core you need to install Serilog.AspNetCore
nuget package.
To write in the file you need to install Serilog.Sinks.File
if not installed automatically.
Where is structured logging in it?
This is the simplest example of log structure :
You can modify it according to your needs.
If you have enjoyed it you can BUY ME A COFFEE :)
Whenever you’re ready, there are 2 ways I can help you:
Promote yourself to 10300+ subscribers by sponsoring this newsletter
Patreon Community: Join and gain access to the 200+ articles I have published so far in one place. Join here