log with Serilog

Log with Serilog in .net 6.0

How to use and set up the log with serilog in ASP.NET 6 Core?

Let’s get started

What is Serilog:

Logging is one of the most crucial things in Application development and It helps to troubleshoot any application issues.

Like many libraries in .Net, Serilog is a structured logging framework that provides diagnostic logging in files, console, database, and elsewhere and it is easy to set up.

Structured logging provides a message format for application Logs and allows them to be treated as data set rather than plain text.

Serilog is so simple like you can send logs via simple configuration. Serilog uses sinks to send you logs to a text file, database, or log management solution.

What are Sinks in Serilog:

Sinks are the targets where you want to send your logs and the most popular sinks are file and console targets.

If you want to create a project in .Net 6, First you have to download the latest SDK version and even you have to update your visual studio code or Visual studio.

As a result, Here is the link to download the latest SDK for .Net 6:

https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-6.0.200-windows-x64-installer

After all, download the latest version of Visual studio code:

https://code.visualstudio.com/download

Hire .NET Developer

Create a new .Net core WebApi application with the below command:

dotnet new webapi -o SerilogWebApiApp

Then add the required package in your SerilogWebApiApp:

dotnet add package serilog.aspnetcore
dotnet add package Serilog.Settings.Configuration
dotnet add package Serilog.Sinks.MSSqlServer

Initialize Serilog in appsettings.json file:

"Serilog": {
  "MinimumLevel": {
    "Default": "Information",
    "Override": {
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
     }
   },
   "WriteTo": [
    {
       "Name": "MSSqlServer",
       "Args": {
         "connectionString":
         "Server=Server-Name;database=DatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true",
         "tableName": "Logs",
         "autoCreateSqlTable": true
       }
    }
  ]
}

Serilog defines different levels of log events. From low to high they are Verbose, Debug, Information, Warning, Error, and Fatal. Basically minimumLevel determines at which level log events are generated.

You can set the minimumLevel you want to log, which means an event for that level and by default, the server uses Error as minimumLevel of recording information.

"MinimumLevel": {
   "Default": "Error",
  }
  • You can change the setting of Default from Error to anything you need.
  • If I want to write log data to MsSqlServer, I wrote MSSqlServer in the Name field of the Serilog setting in the appsettings.json file.
  • I used connectionString in Args where I want to create a log table.
  • I want to create a table automatically, that’s why I set the autoCreateSqlTable property as true.

As you know the program.cs and startup.cs are merged as program.cs in .Net 6 and as we are using.Net 6 here we have to configure Serilog in the program.cs, but if you are using .Net 5 you have to configure Serilog in a startup.cs.

Configure Serilog in Program.cs:

Log.Logger = new LoggerConfiguration().CreateBootstrapLogger();
builder.Host.UseSerilog(((ctx, lc) => lc

.ReadFrom.Configuration(ctx.Configuration)));

You also have to add this line in configure of Program.cs

app.UseSerilogRequestLogging();

CreateBootstrapLogger() sets up Serilog so that the initial logger configuration (which writes only to Console), can be swapped out later in the initialization process, once the web hosting infrastructure is available.

Run SerilogWebApiApp project:

dotnet watch

Call WeatherForecast API from Swagger and see the “Logs” table in SSMS.

Display log data:

  • If any event occurs log will be added to the “Logs” table. We set it to default as information that’s why it adds a log of every event.
  • log
  • Serilog dotnet 6
  • Id: The id column is an optional table identity column. Generally, it defaults to int data type but is also configured as bigint. It is an auto-incrementing unique identity column.
  • Message: It stores the formatted output of log events and defaults to nvarchar(max).
  • MessageTemplate: This column stores log event messages with property placeholders.
  • Level: This column stores log events like information, error, etc.
  • TimeStamp: This column stores log event time with date.
  • Exception: When an exception occurs as a log event, the Exception message automatically appears here.
  • Properties: This column stored log event property value as XML.
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.