Serilog In ASP.NET Core 3.1

Introduction

 
Serilog is a structural logging library for Microsoft .Net and has become the preferred logging library for .Net applications.
 
The stack of features in Serilog that make it an appealing choice for developing apps are: 
  • Serilog's vast ecosystem consisting of hundreds of integrations that cover  Console, File, Message Queue, Seq, Elastic Search, Azure Event Hub etc
  • Simple API and easy to extend
  • The capability of seamless switching the output format to either plain text or Json.

Coding


Let's begin by creating ASP.NET Core WebApi project. Thereafter, install Serilog.AspNetCore nuget package
  1. dotnet add package Serilog.AspNetCore  
Here's the program file generated by Visual Studio/code 
  1. public static void Main(string[] args)  
  2.         {  
  3.             CreateHostBuilder(args).Build().Run();  
  4.         }  
  5.   
  6.         public static IHostBuilder CreateHostBuilder(string[] args) =>  
  7.             Host.CreateDefaultBuilder(args)  
  8.                 .ConfigureWebHostDefaults(webBuilder =>  
  9.                 {  
  10.                     webBuilder.UseStartup<Startup>();  
  11.                 });  
  12.     }  

Console Logging

 
Amend the program file to enable console logging:
  1. public static void Main(string[] args)  
  2.         {  
  3.             Log.Logger = new LoggerConfiguration()  
  4.                 .Enrich.FromLogContext()  
  5.                 .WriteTo.Console()  
  6.                 .CreateLogger();  
  7.             CreateHostBuilder(args).Build().Run();  
  8.         }  
  9.   
  10.         public static IHostBuilder CreateHostBuilder(string[] args) =>  
  11.             Host.CreateDefaultBuilder(args)  
  12.             .UseSerilog()  
  13.                 .ConfigureWebHostDefaults(webBuilder =>  
  14.                 {  
  15.                     webBuilder.UseStartup<Startup>();  
  16.                 });  
  17.     }  
Most logging frameworks provide some way of additional log values across all the log statements. This is useful while providing key information like user id/request id at every log statement.
 
Serilog implements this by what they call  Enrichment and the same can be achieved by using LogContext.
  1. Enrich.FromLogContext()  
From the above line, the code is pretty straightforward and needs no explaination.
 
Out of the box logging configuration in appsettings.json is not necessary. Only the below configuration is required in appsettings.json
  1. {  
  2.   "AllowedHosts""*"  
  3. }  
Let's modify WeatherForecastController class to start logging in the console.
  1. [ApiController]  
  2.     [Route("[controller]")]  
  3.     public class WeatherForecastController : ControllerBase  
  4.     {  
  5.         private static readonly string[] Summaries = new[]  
  6.         {  
  7.             "Freezing""Bracing""Chilly""Cool""Mild""Warm""Balmy""Hot""Sweltering""Scorching"  
  8.         };  
  9.   
  10.         private readonly ILogger<WeatherForecastController> _logger;  
  11.   
  12.         public WeatherForecastController(ILogger<WeatherForecastController> logger)  
  13.         {  
  14.             _logger = logger;  
  15.         }  
  16.   
  17.         [HttpGet]  
  18.         public IEnumerable<WeatherForecast> Get()  
  19.         {  
  20.             _logger.LogInformation("called weather forecast");  
  21.             var rng = new Random();  
  22.             return Enumerable.Range(1, 5).Select(index => new WeatherForecast  
  23.             {  
  24.                 Date = DateTime.Now.AddDays(index),  
  25.                 TemperatureC = rng.Next(-20, 55),  
  26.                 Summary = Summaries[rng.Next(Summaries.Length)]  
  27.             })  
  28.             .ToArray();  
  29.         }  
 After running the application, the output is as follows
  1. [22:16:13 INF] Request starting HTTP/1.1 GET https://localhost:5001/weatherforecast    
  2. 08/30/2020 22:16:10Loaded 'Anonymously Hosted DynamicMethods Assembly'.   
  3. [22:16:13 INF] Executing endpoint 'SerilogVerify.Controllers.WeatherForecastController.Get (SerilogVerify)'  
  4. [22:16:13 INF] Route matched with {action = "Get", controller = "WeatherForecast"}. Executing controller action with signature System.Collections.Generic.IEnumerable`1[SerilogVerify.WeatherForecast] Get() on controller SerilogVerify.Controllers.WeatherForecastController (SerilogVerify).  
  5. 08/30/2020 22:16:10[22:16:13 INF] called weather forecast  
  6. 08/30/2020 22:16:10[22:16:14 INF] Executing ObjectResult, writing value of type 'SerilogVerify.WeatherForecast[]'.  
  7. 08/30/2020 22:16:10Loaded   
  8. [22:16:14 INF] Executed action SerilogVerify.Controllers.WeatherForecastController.Get (SerilogVerify) in 75.9537ms  
  9. 08/30/2020 22:16:10[22:16:14 INF] Executed endpoint 'SerilogVerify.Controllers.WeatherForecastController.Get (SerilogVerify)'  
We can see the log message being called for the Weather Forecast as "called weather forecast".
 
We can easily change the output format to JSON.
  1. public static void Main(string[] args)  
  2.         {  
  3.             Log.Logger = new LoggerConfiguration()  
  4.                 .Enrich.FromLogContext()  
  5.                 .WriteTo.Console(new RenderedCompactJsonFormatter())  
  6.                 .CreateLogger();  
  7.             CreateHostBuilder(args).Build().Run();  
  8.         }  
  9.   
  10.         public static IHostBuilder CreateHostBuilder(string[] args) =>  
  11.             Host.CreateDefaultBuilder(args)  
  12.             .UseSerilog()  
  13.                 .ConfigureWebHostDefaults(webBuilder =>  
  14.                 {  
  15.                     webBuilder.UseStartup<Startup>();  
  16.                 });  
  17.     }  

File Logging

 
Install the Serilog.Sinks.File nuget package
  1. dotnet add package Serilog.Sinks.File  
 To configure the sinks in C# code, call WriteTo.File() while logging configuration
  1. public static void Main(string[] args)  
  2.         {  
  3.             Log.Logger = new LoggerConfiguration()  
  4.                 .Enrich.FromLogContext()  
  5.                 .WriteTo.Console(new RenderedCompactJsonFormatter())       .WriteTo.Debug(outputTemplate:DateTime.Now.ToString())          .WriteTo.File("log.txt",rollingInterval:RollingInterval.Day)  
  6.                 .CreateLogger();  
  7.             CreateHostBuilder(args).Build().Run();  
  8.         }  
  9.   
  10.         public static IHostBuilder CreateHostBuilder(string[] args) =>  
  11.             Host.CreateDefaultBuilder(args)  
  12.             .UseSerilog()  
  13.                 .ConfigureWebHostDefaults(webBuilder =>  
  14.                 {  
  15.                     webBuilder.UseStartup<Startup>();  
  16.                 });  
  17.     }  
The rolling interval appends the time period of the file name such as log20200830.txt
 

Seq

 
Seq has a splendid support for Serilog's feature such as complex event data, enrichment and structural logging.
 
You can use docker for Seq using the below command.
  1. docker pull datalust/seq  
  2. docker run --name seq -d --restart unless-stopped -e ACCEPT_EULA=Y -p 5341:80 datalust/seq:latest  
You can see Seq is running on the port number 5341.
 
Install Serilog.Sinks.Seq nuget package
  1. dotnet add package Serilog.Sinks.Seq  
 To configure the sinks in C# code, call WriteTo.Seq() while logging configuration
  1. public static void Main(string[] args)  
  2.         {  
  3.             Log.Logger = new LoggerConfiguration()  
  4.                 .Enrich.FromLogContext()  
  5.                 .WriteTo.Console(new RenderedCompactJsonFormatter())  
  6.                 .WriteTo.Debug(outputTemplate:DateTime.Now.ToString())  
  7.                 .WriteTo.File("log.txt",rollingInterval:RollingInterval.Day)  
  8.                 .WriteTo.Seq("http://localhost:5341/")  
  9.                 .CreateLogger();  
  10.             CreateHostBuilder(args).Build().Run();  
  11.         }  
  12.   
  13.         public static IHostBuilder CreateHostBuilder(string[] args) =>  
  14.             Host.CreateDefaultBuilder(args)  
  15.             .UseSerilog()  
  16.                 .ConfigureWebHostDefaults(webBuilder =>  
  17.                 {  
  18.                     webBuilder.UseStartup<Startup>();  
  19.                 });  
  20.     }  
 Added additional HTTP Get method to validate error logging in WeatherForecastController.
  1. [HttpGet(template:"/api/error/{id}")]  
  2.         public ActionResult<string> GetError(int id)  
  3.         {  
  4.             try  
  5.             {  
  6.                 if (id <= 0)  
  7.                 {  
  8.                     throw new Exception($"id cannot be less than or equal to 0:{id}");  
  9.                 }  
  10.   
  11.                 return Ok($"id is:{ id}");  
  12.   
  13.             }  
  14.             catch (Exception ex)  
  15.             {  
  16.                 var sb = new StringBuilder();  
  17.                 sb.AppendLine($"Error message:{ex.Message}");  
  18.                 sb.AppendLine($"Error stack trace:{ex.StackTrace}");  
  19.                 _logger.LogError(sb.ToString());  
  20.             }  
  21.   
  22.             return BadRequest("bad request");  
  23.         }  
Now run the application & navigate to /api/error/0 and open the Seq by running http://localhost:5341
 
 
I hope you like the article. In case, you find the article interesting then kindly like and share it.