Structured Logging Using "SeriLog" Log Provider In ASP.NET Core Logging

Logging

Logging is an essential part of software development. It provides developers and support teams with special 'glasses' which enable them to see what the application code is really doing.

Prior to .NET Core, we used to inject a logger into the classes and we needed to introduce a dependency on a 3rd party library . In .NET Core, you don’t have a dependency on a 3rd party library’s namespace – just a namespace provided by Microsoft. By default Asp.net Core has option debug to Console, EventSource.

What is Serilog

Serilog is a logging framework for logging structured data. This framework is built around the idea that log messages should be more than a collection of strings. Log messages are preserved as structured data(JSON) that can be written in document form to a variety of output providers. (https://serilog.net/)

Steps to integrate Serilog in ASP.NET Core using Visual Studio Code.

Install the following,

For the demo purpose I have used Web Application.

Step1 : Create a web app with dotnet

  • mkdir DemoSeriLog
  • cd DemoSeriLog
  • dotnet new mvc

Open the DemoSeriLog folder in Visual Studio Code (VS Code) and select the Startup.cs file.

  • Select Yes to the Warn message "Required assets to build and debug are missing from DemoGoogleChart . Add them?"
  • Select Restore to the Info message "There are unresolved dependencies".

Step 2

Install NuGet Package Manager extension. After you've installed it, to add a package, press Ctrl+P, type > nuget and press Enter.

  • Then, select "NuGet Package Manager:Add Package"
  • Enter package name : Serilog
  • Select package name and version
ASP.NET Core

ASP.NET Core

ASP.NET Core

ASP.NET Core

Step 3 

Follow the same procedure to add “Serilog.Extensions.Logging.File” as in Step1.

Step4  

In the Startup.cs, add the below code line in Configure method and increase the parameter in Configure method.

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  2. loggerFactory.AddFile("Logs/myapp-{Date}.txt);  
ASP.NET Core

Step5

Go to HomeController and  add dependency using constructor.  Update the Constructor to Inject ILogger interface implementor.

  1. public class HomeController: Controller {  
  2.         private readonly ILogger _logger;  
  3.         public HomeController(ILogger < HomeController > logger) {  
  4.             _logger = logger;  
  5.         }  
Step6

Calling logging method in i.e. LogInformation
  1. public IActionResult Index()  
  2. {  
  3.    _logger.LogInformation("Demo Logging Information in Index Method");  
  4.    return View();  
  5. }   
Step7

Logs will be written into a file system.

ASP.NET Core

That’s it. Thanks for reading.
Ebook Download
View all
Learn
View all