Logging with Serilog in .NET

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

Logging with Serilog in .NET

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 :

Logging with Serilog in .NET

Now we can call this in Program.cs :

Logging with Serilog in .NET

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 :

Logging with Serilog in .NET

This is all that we need to do, wondering how this would be read. This part is doing that magic

Logging with Serilog in .NET

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 :

Logging with Serilog in .NET

Let’s call it in our Program.cs now

Logging with Serilog in .NET

How to use the logger in the controller or any other class?

Just inject ILogger with your desired class like this and use it :

Logging with Serilog in .NET

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

Logging with Serilog in .NET

You can modify it according to your needs.

This article was originally published at https://mwaseemzakir.substack.com/ on .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place