How to use Serilog in ASP.NET Core Web API for Beginners with Example

How to Use Serilog in ASP.NET Core Web API for beginners with example

Serilog is one of the most popular and widely used logging libraries by developers for .NET applications. It offers several benefits when compared to other logging libraries available on the market.

What is Logging? Basically Logging is an essential part of any application. It helps developers understand what's happening in the application, diagnose issues, and troubleshoot problems.


Why you need to consider Serilog instead of other logging libraries?


Scalability and Performance:
Serilog is designed to handle large volumes of log data efficiently. Serilog is well optimized for performance. It was also designed with minimal impact on the application's performance while logging through features such as asynchronous logging, lazy message generation, and support for log message batching.

Extensibility:

Serilog is highly extensible and it has more than 90+ provided sinks, including popular logging services such as

  • Amazon DynamoDB
  • Azure Blob Storage
  • Azure CosmosDB
  • ElasticSearch
  • Google Cloud StackDriver
  • MariaDB
  • MongoDB
  • PostgreSQL
  • SQLite
  • SQL Server and so on

It includes general-purpose sinks such as file and console sinks. You will learn how to log messages in a file and on the console in the following example. Serilog provides an advanced plug-in architecture that allows developers to extend the library with custom sinks and enrichers.

 

You can see more details about provided sinks in Serilog here.


Flexible and structured logging:

Serilog provides a simple and flexible logging API that allows us to capture structured logs in a wide range of formats, including JSON, plain text, and XML.

It helps you and your team analyse the application, and you can use that data to make a more optimized version of your application.


Integration with popular .NET frameworks: 

Serilog is most popularly used within the .NET community and it has built-in integration with popular .NET frameworks, such as ASP.NET Core, Entity Framework, and Microsoft.Extensions.Logging.


Community Support:

Serilog is backed with a large community of active developers who contribute to the development of the framework, they are always ready to share knowledge and provide support. you can see more about in Github repos here


How to Configure the Serilog:

In this blog, I'm giving two examples. The First example shows how to log the information to a text file using File Sink and Second example shows how to log the information to Console and a Text file using separate configuration json file for Serilog with the help of Console and File Sinks.

You can clone My Github Repository to try this example here

Open Visual Studio Application → create a new project select ASP.NET Core Web API Template Give a name for your Project Also make sure .NET 6.0 is selected in Framework dropdown additional information page Click Create 


After the project was created If you try to run the project Debug or Press F5.It will open a Swagger API Web Page in the New Browser window and you will see the console like in the image below.


How to Use Serilog in ASP.NET Core Web API

How to install Serilog dependencies:

You need to install dependencies before implementing the code. you can do with two ways one is through GUI or another one is Package Manager Console.


GUI:

In Solution Explorer Window → your project name → Dependencies → right click Packages → Manage NuGet Packages.


It opens NuGet package manager in that browse tab → search for Serilog.AspNet.Core → install that package as shown in the image below.


How to Use Serilog in ASP.NET Core Web API

Package Manager Console:

You can also install dependencies through Package Manager Console. To do this click Tools NuGet Package Manager Package Manager Console. It brings the console and execute the following commands for install Serilog dependencies.

First Example:

In this first example I'm going to log the information to notepad file using serilog file sink. You can find the explanations for functions and attributes used in this blog here.


Open program.cs file. Change the code in that file, which is given below.



Open appsettings.json, Change the code in that file, which is given below.


In Solution Explorer window → Controllers → WeatherForecastController.cs. Replace the following code.


Debug the project Press F5.

It opens a SwaggerAPI Page in browser, try to hit the GetWeatherForecast Endpoint. 

How to Use Serilog in ASP.NET Core Web API

It creates logs folder in your Project folder and webapi txt file inside that folder. If you open that webapi txt file it contains log of the project.

How to Use Serilog in ASP.NET Core Web API


How to Use Serilog in ASP.NET Core Web API

Second Example:

How to configure Serilog Properties in separate json file instead of appsettings.json file?

    In this example, It will log information in file and console by using separate configuration file for Serilog properties. If you want to try second example please follow the steps of first example it contains basic configuration of the Serilog or you can simply clone my Github repo here


    You need to add one json file for this scenario. In Solution explorer window → right click the project name add → New Item → select json file. I was added json file name as seri-log.config.json.


How to Use Serilog in ASP.NET Core Web API

I added the code in the given code snippet.


It has two sinks one is file that will log the information in text file and another one is console that will log the information in console.


Also you need to change the program.cs file code that will read the configuration from the newly created json file.That code also given in code snippet.



After following the steps, press F5


Now the log information shows in the console, too.

How to Use Serilog in ASP.NET Core Web API

Methods and Serilog Properties Explanations:

new LoggerConfiguration() - This method creates a new LoggerConfiguration object that will be used to configure the Serilog logger.

ReadFrom.Configuration(builder.Configuration) - This method is used to configure the logger based on the application's configuration. This method uses the builder.Configuration object to read the configuration settings and apply them to the logger.

Enrich.FromLogContext() - This method is used to add contextual information to log events. This will allow log events to be enriched with additional information, such as the name of the current method or the user that initiated the event.

CreateLogger() - This method is used to create the Serilog logger.

builder.Logging.ClearProviders() - It can be called on an instance of ILoggerFactory in a .NET application to remove all the logging providers from the logging pipeline.

builder.Logging.AddSerilog(logger) - This method is used to add a Serilog logger to the logging pipeline of a .NET application.

AddJsonFile("seri-log.config.json") - Configuration object that reads from a JSON file named "seri-log.config.json" (using the AddJsonFile() method) and then passes that configuration object to the ReadFrom.Configuration() method.

Build() - After the configuration file has been loaded, it can be built into a Configuration object by calling the Build().

Using: This property is an array of strings that specifies the Serilog packages that will be used by the logger.

MinimumLevel: This important property you need to remember while configuring the Serilog. This property specifies the minimum logging level for the logger. Serilog has 6 level minimum levels.

  • Verbose: It used to track low level of severity. It is the noisiest level. Rarely enabled for a production app.
  • Debug: Debug is mostly used by developer team to know about your application internal events not necessarily observable from the outside.
  • Information: Information is used for log the general information how the flow happens in your application.
  • Warning: Warning is used to log the information not needed to take immediate action now but those may need attention future.
  • Error: Error is used to log functionality not working or broken . This types need immediate attention.
  • Fatal: Fatal is used to log critical level that will cause application crash. This types also need immediate attention.

Example: If you choose a higher level, it will log the lower level by default.If you choose minimum level as Warning it logs warning, information, Debug and Verbose level Details.

WriteTo: This property is an array of objects that specifies the log sinks to which the log events will be written.

Name: This property specifies the name of the sink.

Path: property is used to specify the path to the log file that will be written by the File sink.

RollingInterval - property is used to specify how often to create a new log file. The log file name will include the date in the format specified by the rollingInterval property, with the specified file path and file extension.

OutputTemplate - property accepts a string value that can include placeholders for various pieces of information that are associated with each log event. It contains following placeholders in this example,

{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}: The date and time of the log event, in the format yyyy-MM-dd HH:mm:ss.fff zzz.

{CorrelationId}: A unique identifier for the request or operation associated with the log event, if one is available.

{Level:u3}: The log level of the event, abbreviated to three characters.

{Username}: The username associated with the request or operation, if one is available.

{Message:lj}: The log message associated with the event, left-justified and trimmed to fit within the maximum message length.

{Exception}: Any exception that is associated with the log event.

{NewLine}: A new line character.

Summary:

    Serilog is easy to use and configure and implement the structured logging in your .net application. It provides a wide variety of sinks that will give us to easily log your application information based on your needs. Based on those information, you will understand the events, errors and performance metrics of your application. In hard times it helps to troubleshoot the application issues. If you are looking for good logging framework its worth for give it a try to Serilog.

Previous Post Next Post