Log Data Into File Using Serilog Framework In Blazor Server App

Introduction

 
Logging is a very critical and essential part of any software. It helps us in the investigation of the essence of problems. The Blazor server uses ASP.net core logging framework that supports various logging providers. It also supports third party logging providers such as Serilog.
 
Serilog is a good logging framework and it is built with the structured log data in mind. It is a kind of serializer. Serilog determines the right representation when the properties are specified in log events.
 
The Serilog provides various sinks to log the data into file, MSSQL, etc. The serilog also supports ASP.net core and same sinks we can use for Blazor server app.
 
To use Serilog in Blazor server app, we need to add the dependency of "Serilog.AspNetCore". The dependency package can be installed either using NuGet package manager or using dotnet core CLI.
 
Following are the steps to configure Serilog file sink in Blazor server app.
 
Step 1 - install "Serilog.AspNetCore" package
 
We can either install said package using NuGet package Manager or dotnet core CLI. Using following command, we install said package using NuGet package.
  1. PM> Install-Package Serilog.AspNetCore  
We can also install specific version of above package by defining the version using “-Version {number}” syntax.
 
Step 2 - Configure Serilog in Blazor server app
 
The Serilog need to configure for Blazor server app in Program.cs file. To configure the sink in c# code, we need to call WriteTo.File method during logger configuration. The logger configuration needs to write in a Main method of program class.
  1. Log.Logger = new LoggerConfiguration()  
  2. .Enrich.FromLogContext()  
  3. .WriteTo.File(@"C:\logs\log.txt")  
  4. .CreateLogger();  
  5. CreateHostBuilder(args).Build().Run();  
Step 3 - Set Serilog providers
 
We can set Serilog log provides using “UseSerilog” method of SerilogHostBuilderExtensions class.
  1. public static IHostBuilder CreateHostBuilder(string[] args) =>  
  2.     Host.CreateDefaultBuilder(args)  
  3.     .UseSerilog()  
  4.         .ConfigureWebHostDefaults(webBuilder =>  
  5.         {  
  6.             webBuilder.UseStartup<Startup>();  
  7.         });  
Now Serilog is configured to use for Blazor server app. Using Log extension methods, we can log in to file based on log level. The Serilog provides various extension method to log data and Serilog framework dump log data into file if extension’s method log level is greater than minimum log level. The default value of minimum log level is “Verbose”. If we do not specify the minimum log level, Serilog use default log level and log all data.
 
Example
  1. @page "/counter"  
  2. @using Serilog;  
  3. <h1>Counter</h1>  
  4.   
  5. <p>Current count: @currentCount</p>  
  6.   
  7. <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>  
  8.   
  9. @code {  
  10.     private int currentCount = 0;  
  11.   
  12.     private void IncrementCount()  
  13.     {  
  14.         Log.Information($"Counter button click: {DateTime.Now}");  
  15.         currentCount++;  
  16.     }  
  17. }  
Output
 
 
The Serilog allows us to do configuration for logging such as define rolling interval, text file format, file path, minimum logging level, etc. The WriteTo.File method allows us to specify some of the configuration.
 
Example
 
In the following example, some configurations are set like the rolling interval set to day, set minimum logging level to error and customize output file format.
  1. .WriteTo.File(@"C:\logs\log.txt",   
  2.                     restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Error,  
  3.                     rollingInterval: RollingInterval.Day,  
  4.                     outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")  
Output
 
 
Summary
 
Serilog is a logging framework that has many built-in sinks available for structured log data. In this article, I have explained about Serilog File sink (that is available in default package) for Blazor server app.


Similar Articles