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
-
NLog
-
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.
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place