Serilog In .NET Core

As we know, logging is one of the most important topics for any kind of small or big application in software.
 
With the help of logging not only can we track what's happing behing the application, but also it helps to track any kind of exception. This exception actually comes iton application when it shows the exact method and line numnber with proper message details. So with the help of logging, developers can easily understand what the actual error is. 
 
So I have decided to write a short summary on Serilog in ASP.NET Core 3.1 and its implementations.
 
As we know that .NET Core has some basic logging features built-in which we have seen in the ILogger interface throughout the.NET Core Application.
 
But sometimes that's not enough.  So what if we want more control over how and where to log the details?
This is where Logging Frameworks comes into the picture. 
 
So Serilog is one of the most popular Libraries for ASP.NET Core Applications.
 
Here in this section I will try to cover the following topics:
  1. What is Serilog?
  2. Setup .NET Core Project
  3. Logging with the Default Logger
  4. Log Levels
  5. Packages Installation
  6. Console Logging.
  7. File Logging.
  8. Database Logging.
  9. Summary

Introduction

 
What is Serilog?
 
From the official site:https://serilog.net/, "Serilog provides diagnostic logging to files, the console, and elsewhere. It is easy to set up, has a clean API, and is portable between recent .NET platforms. Unlike other logging libraries, Serilog is built with powerful structured event data in mind."
 
Setup .NET Core Project
 
For the step by step implementations we will create a simple .NET Core Web Application. I am using Visual Studio 2019. I will create a new project and then select ASP.NET Core Web Application project with an empty project template.
 
Here few default files would be  as follows, 
  • appsettings.json,
  • appsettings.Development.json,
  • Startup.cs 
  • Program.cs.
The default Program.cs file would look like this,
  1. public class Program {  
  2.     public static void Main(string[] args) {  
  3.         CreateHostBuilder(args).Build().Run();  
  4.     }  
  5.     public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => {  
  6.         webBuilder.UseStartup < Startup > ();  
  7.     });  
  8. }  
Logging with the Default Logger
 
As we can see the default logging configuration can be found in app setting.json.
  1. {  
  2.     "Logging": {  
  3.         "LogLevel": {  
  4.             "Default""Information",  
  5.             "Microsoft""Warning",  
  6.             "Microsoft.Hosting.Lifetime""Information"  
  7.         }  
  8.     }  
  9. }   
Here I have just used test action to show the default log,
  1. [HttpGet]  
  2. [Route("LoggTest")]  
  3. public IActionResult LoggTest() {  
  4.     _logger.LogInformation("normal log");  
  5.     int count;  
  6.     try {  
  7.         for (count = 0; count <= 1; count++) {  
  8.             if (count == 1) {  
  9.                 throw new Exception("default test exception");  
  10.             }  
  11.         }  
  12.         return Ok();  
  13.     } catch (Exception ex) {  
  14.         _logger.LogError(ex, "Exception catch log");  
  15.         return BadRequest(ex.Message);  
  16.     }  
  17. }  
Please see the image below.
 
 
 
This console log will be visible once you switch to Kestrel Webserver.
 
Note
Do not forget to add dependency Injection in controller constructor.
 
Log Levels
 
There are the following log-levels availabe here,
  • Trace – Detailed messages with sensitive app data.
  • Debug – Useful for the development environment.
  • Information – General messages, like the way we mentioned earlier.
  • Warning – For unexpected events.
  • Error – For exceptions and errors.
  • Critical – For failures that may need immediate attention.
Packages Installation
Now we have see how to apply default logging. Let's see how to implement Serilog step by step.
 
First of all we need to know what library we need to install.
 
So here are the libraries listed below,
  1. Install-Package Serilog.AspNetCore    
  2. Install-Package Serilog.Settings.Configuration    
  3. Install-Package Serilog.Enrichers.Environment    
  4. Install-Package Serilog.Enrichers.Process    
  5. Install-Package Serilog.Enrichers.Thread   
Now here we have installed all the required Serilog packages, so let’s go ahead and configure Serilog.
 
Console Logging
 
For console logging we don't need to do much extra setup. Here you can see the log in the console window.
 
For this, we will be required to do the basic setup to configure Serilog at the entry point in .NET Core Application. Here in the Program.cs file.do the following changes.
  1. public static void Main(string[] args) {  
  2.     //Read Configuration from appSettings    
  3.     var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();  
  4.     //Initialize Logger    
  5.     Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(config).CreateLogger();  
  6.     try {  
  7.         Log.Information("Application Starting.##############3");  
  8.         CreateHostBuilder(args).Build().Run();  
  9.     } catch (Exception ex) {  
  10.         Log.Fatal(ex, "The Application failed to start.######333");  
  11.     } finally {  
  12.         Log.CloseAndFlush();  
  13.     }  
  14.     //CreateHostBuilder(args).Build().Run();    
  15. }  
Here in createhost method we need to do 1 line of change like this,
  1. public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).UseSerilog() //Uses Serilog instead of default .NET Logger    
  2.     .ConfigureWebHostDefaults(webBuilder => {  
  3.         webBuilder.UseStartup < Startup > ();  
  4.     });  
Now run the application and see the image below,
 
 
File Logging
 
Now for the file log we need to do some setup in our appconfig.json file. Please use this setting just copy and paste the following configuration.
  1. "Serilog": {  
  2.     "MinimumLevel": {  
  3.         "Default""Information",  
  4.         "Override": {  
  5.             "Microsoft""Warning",  
  6.             "System""Warning",  
  7.             "System.Net.Http.HttpClient""Warning"  
  8.         }  
  9.     },  
  10.     "WriteTo": [{  
  11.         "Name""Console"  
  12.     }, {  
  13.         "Name""Logger",  
  14.         "Args": {  
  15.             "configureLogger": {  
  16.                 "Filter": [{  
  17.                     "Name""ByIncludingOnly",  
  18.                     "Args": {  
  19.                         "expression""Contains(SourceContext, 'AspNetCoreSerilogDemo.TestLogApi') and (@Level = 'Error' or @Level = 'Fatal' or @Level = 'Warning')"  
  20.                     }  
  21.                 }],  
  22.                 "WriteTo": [{  
  23.                     "Name""File",  
  24.                     "Args": {  
  25.                         "path""Logs/Error/applog_.log",  
  26.                         "outputTemplate""{Timestamp:o} [Thread:{ThreadId}] [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",  
  27.                         "rollingInterval""Day",  
  28.                         "retainedFileCountLimit": 7  
  29.                     }  
  30.                 }]  
  31.             }  
  32.         }  
  33.     }, {  
  34.         "Name""Logger",  
  35.         "Args": {  
  36.             "configureLogger": {  
  37.                 "Filter": [{  
  38.                     "Name""ByIncludingOnly",  
  39.                     "Args": {  
  40.                         "expression""Contains(SourceContext, 'AspNetCoreSerilogDemo.TestLogApi') and @Level = 'Information'"  
  41.                     }  
  42.                 }],  
  43.                 "WriteTo": [{  
  44.                     "Name""File",  
  45.                     "Args": {  
  46.                         "path""Logs/Info/applog_.log",  
  47.                         "outputTemplate""{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",  
  48.                         "rollingInterval""Day",  
  49.                         "retainedFileCountLimit": 7  
  50.                     }  
  51.                 }]  
  52.             }  
  53.         }  
  54.     }],  
  55.     "Enrich": ["FromLogContext""WithMachineName""WithThreadId""WithThreadName"],  
  56.     "Properties": {  
  57.         "Application""AspNetCoreSerilogDemo"  
  58.     }  
  59. }  
Now run the application, then check your application. As you can see 1 folder is created by Name of Logs, and inside this folder we have 2 folders, error and info for logging
separately. Open the folder and you will be able to see some logs there.
 
Refer to these images as well.
 
 
 
Database Logging.
 
Now the last point is to log exception in Db and  for that we need to install one more package,
 
Install-Package Serilog.Sinks.MSSqlServer
 
After installing this packege you need to add some configuration in appsettings.json file,
 
Please use the same as below,
  1. "WriteTo": [{  
  2.     "Name""File",  
  3.     "Args": {  
  4.         "path""Logs/Info/applog_.log",  
  5.         "outputTemplate""{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",  
  6.         "rollingInterval""Day",  
  7.         "retainedFileCountLimit": 7  
  8.     }  
  9. }, {  
  10.     "Name""MSSqlServer",  
  11.     "Args": {  
  12.         "connectionString""Data Source =...;Initial Catalog=yourDb;User Id =yourId; Password =yourpwd;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",  
  13.         "sinkOptionsSection": {  
  14.             "tableName""Logs",  
  15.             "schemaName""yourDbName",  
  16.             "autoCreateSqlTable"true  
  17.         },  
  18.         "restrictedToMinimumLevel""Warning"  
  19.     }  
  20. }]  
Note
You don't need to create your own table Logs, once the application will start for execution, this table will automatically create.
 
After excecuting the application you will be able to see the log for this table.
 
Please refer to the image below,
 
 

Summary

 
Finally we have completed step by step learning logging with default logger provided by Microsoft. Then after that we have learned how to implement Serilog, then after that we have seen practically how to log in console file, then finally in database which is more important to understand.
 
Kindly let me know if you face any issue, I will try my best to resolve as much as possible. I hope you liked this tutorial; please share it with others. Thank you for taking your valuable time to read the full article.


Similar Articles