Serilog in ASP.NET Core Web Application

In this tutorial, we are going to use Serilog in ASP NET Core Web Application. In my previous article, we extend the functionality of the ASP.NET Core logging extension using Nlog. This time, we will use Serilog, which can also be added to your ASP.NET Core Application using NuGet Manager.

What is Serilog?

Serilog is a portable and structured logging framework to record diagnostic logs into files, console and SQL databases. Serilog makes it easy to record custom object properties and even output your logs to JSON. This logging provider also has enrichers that help you logs event such as Serilog.Enrichers.Environment which logs events with properties from System.Environment.

Before we start please make sure to have this following application installed on your machine.

  • The latest version of Visual Studio
  • Alternatively, you can also use Visual Studio Code
  • SQL SERVER
  • .Net Core SDK 3.1

I. Create a new ASP.NET Core Web Application

  1. First, create your ASP.NET Core Web Application. To do that just follow the steps below.
  • Select File > New > Project.
  • Select ASP.NET Core Web Application. Name the project SerilogDemo to have the same namespace as my project. Click OK.
  • Select an ASP.NET Core Web Application. and then uncheck Configure for HTTPS.
  • Lastly, Click on Create.
ASP.NET Core Web Applciation Settings

2. Now we need to install required packages for this project. I have listed it all below.

PackageDescription
Serilog.AspNetCoreSerilog support for ASP.NET Core logging
Serilog.Settings.ConfigurationMicrosoft.Extensions.Configuration (appsettings.json) support for Serilog.
Serilog.Enrichers.EnvironmentEnrich Serilog log events with properties from System.Environment.
Serilog.Enrichers.ProcessThe process enricher for Serilog.
Serilog.Enrichers.ThreadEnrich Serilog events with properties from the current thread.
Serilog.Sinks.SeqSerilog sink that writes to the Seq log server over HTTP/HTTPS.
NuGet Packages

Use NuGet Package Manager to install this package. If this is your first time using this, you can visit this article.

II. Configure Serilog on Program.cs

  1. Add the following code snippet on your program.cs under Main method.
        var configuration = new ConfigurationBuilder()
                 .AddJsonFile("appsettings.json")
                 .Build();
  
             Log.Logger = new LoggerConfiguration()
                 .ReadFrom.Configuration(configuration)
                 .CreateLogger();
             try
             {
                 Log.Information("Application starting up");
                 CreateHostBuilder(args).Build().Run();
             }
             catch (Exception ex)
             {
                 Log.Error(ex, "The application failed to start");
                 throw;
             }
             finally
             {
                 Log.CloseAndFlush(); //close logs that is not written yet
             } 

2. Add Serilog provider inside CreateHostBuilder method using the code below.

Host.CreateDefaultBuilder(args)
                 .UseSerilog()  
                 .ConfigureWebHostDefaults(webBuilder =>
                 {
                     webBuilder.UseStartup();
                 });

Below is the full program.cs code:

 using Microsoft.AspNetCore.Hosting;
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.Hosting;
 using Microsoft.Extensions.Logging;
 using Serilog;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
  
 namespace SerilogDemo
 {
     public class Program
     {
         public static void Main(string[] args)
         {
             var configuration = new ConfigurationBuilder()
                 .AddJsonFile("appsettings.json")
                 .Build();
  
             Log.Logger = new LoggerConfiguration()
                 .ReadFrom.Configuration(configuration)
                 .CreateLogger();
             try
             {
                 Log.Information("Application starting up");
                 CreateHostBuilder(args).Build().Run();
             }
             catch (Exception ex)
             {
                 Log.Error(ex, "The application failed to start");
                 throw;
             }
             finally
             {
                 Log.CloseAndFlush(); //close logs that is not written yet
             }
  
         }
  
         public static IHostBuilder CreateHostBuilder(string[] args) =>
             Host.CreateDefaultBuilder(args)
                 .UseSerilog()
                 .ConfigureWebHostDefaults(webBuilder =>
                 {
                     webBuilder.UseStartup<Startup>();
                 });
     }
 }

III. Add dummy logs

Open HomeController, let’s add some logs information to be displayed. I added the logs from the default method of my HomeController, which is the index and the privacy page. See the code snippet below.

Index Method » Home Page:

public IActionResult Index()
         {
             _logger.LogInformation("This is the Home Page");
             return View();
         }

Privacy Method » Privacy Page

 public IActionResult Privacy()
         {
             _logger.LogInformation("Privacy Page");
  
  
             try
             {
                 throw new Exception(); //dummy excemption error for our logs
             }
             catch (Exception ex)
             {
                 _logger.LogError(ex, "This excemption is in Privacy page");
             }
             return View();
         } 

IV. Configure Serilog Console Logging

Since we added appsettings.json to our configuration on the program.cs class, we will use appsettings.json for our serilog configuration. Open your appsettings.json and add the following code snippet. This snippet also applies serilog enriched, which we added a while ago using the NuGet Package Manager.

 {
   "AllowedHosts": "*",
   "Serilog": {
     "Using": [],
     "MinimumLevel": {
       "Default": "Information",
       "Microsoft": "Warning",
       "System": "Warning"
     },
     "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
     "WriteTo": [
       { "Name": "Console" } 
     ]
   }
 } 
Serilog in ASP NET Core Web Application - console logging

V. Configure Serilog File Logging

To enable file logging use the code below. This will create a txt file with log.txt filename.

{
         "Name": "File",
         "Args": {
           "path": "D:\test_project\Serililog\log.txt",
           "outputTemplate": "{Timestamp:G} {Message}{NewLie:1}{Exception:1}"
         }
  }

Your appsettings.json will now look like this.

 {
   "AllowedHosts": "*",
   "Serilog": {
     "Using": [],
     "MinimumLevel": {
       "Default": "Information",
       "Microsoft": "Warning",
       "System": "Warning"
     },
     "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
     "WriteTo": [
       {
         "Name": "File",
         "Args": {
           "path": "D:\\test_project\\Serililog\\log.txt",
           "outputTemplate": "{Timestamp:G} {Message}{NewLie:1}{Exception:1}"
         }
       }
     ]
   }
 } 

Here is how my file look like.

Serilog in ASP NET Core Web Application - File logging

VI. Configure Serilog Json File Logging

To enable file logging use the code below.

{
         "Name": "File",
         "Args": {
           "path": "D:\test_project\Serililog\log.json",
           "formatter": "Serilog.Formatting.Json.JsonFormatter,Serilog"
         }
       }

Your appsettings.json will now look like this.

 {
   "AllowedHosts": "*",
   "Serilog": {
     "Using": [],
     "MinimumLevel": {
       "Default": "Information",
       "Microsoft": "Warning",
       "System": "Warning"
     },
     "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
     "WriteTo": [
       {
         "Name": "File",
         "Args": {
           "path": "D:\\test_project\\Serililog\\log.json",
           "formatter": "Serilog.Formatting.Json.JsonFormatter,Serilog"
         }
       }
     ]
   }
 } 

This is my JSON file look like. See the image below.

JSON File logging in Serilog in ASP NET Core Web Application

VII. Configure Serilog Seq Sink

If you review the NuGet Packages that we added a while ago you will see that we added Serilog.Sinks.Seq. This sink will allow us to writes to the Seq log server over HTTP/HTTPS. Seq offers an admin dashboard where you can view your logs.

  1. Below is the seq event logs where you can browse the details of the error or information that you logs.
Seq Sink in Serilog in ASP NET Core Web Application

2. Seq also provided a dashboard the errors and exception that is encountered by your application. See the image below.

Seq Sink Dashboard Serilog in ASP NET Core Web Application

3. To install Seq you may go to Seq download page which is here. You have two available option if you are in windows you can directly download the msi installer. You can also use docker to install seq.

Download Seq for windows
Seq Download Page

4. Here’s is how you can configure seq sink. Please see the code snippet below.

{
   "AllowedHosts": "*",
   "Serilog": {
     "Using": [],
     "MinimumLevel": {
       "Default": "Information",
       "Microsoft": "Warning",
       "System": "Warning"
     },
     "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
     "WriteTo": [
       {
         "Name": "Seq",
         "Args": {
           "serverUrl": "http://localhost:5341/"
         }
       }
     ]
   }
 }

Here’s a seq documentation on how you can install it on windows. Install Seq on WIndows.

You can download the source code in my GitHub account @coderbugzz.

Summary

In this tutorial, we have shown you how easy it is to configure Serilog in ASP NET Core Web Application. We also added a seq sink which offers more than just logging to a file. If this tutorial helps you please follow me on my Facebook page @freecodespot.

KEEP CODING!