WHAT'S NEW?
Loading...

What is Logging and How it Works (Serilog)

What is Logging?

It's very difficult to find Bugs and Diagnose the Code, In order to Diagnose a Project their are various Logging tools available. Logging is an approach to record information about Program's execution for debugging and tracing purposes. It usually involves writing text messages to log files or sending data to monitoring applications. The logged data gives the good understanding of errors and warnings. In .Net there are Multiple Logging Frameworks are available:
They are designed for simplifying developers work regarding processing logs. All the frameworks works on same principle you include one of the libraries into your program and add logging code and when you run your Program Logging Information is sent to configured logging destination like: Console, File and Database.

In this Article, I am going to teach you how to work with a logging tool. ELMAH and Serilog are one of the best framework present in the market. In this tutorial, i will be using Serilog for Debugging code.

Why Serilog?

Like many other libraries for .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.

Structure of Serilog:

serilog-structure

How Serilog Works?

  • First of all, Add the Following NuGet Packages in your Project.
Serilog.AspNetCore
Serilog.Extensions.Logging 
Serilog.Sinks.ColoredConsole
  • After adding the Dependencies, Edit your Program.cs file:
1:  using Microsoft.AspNetCore;  
2:  using Microsoft.AspNetCore.Hosting;  
3:  using Serilog;  
4:  using Serilog.Events;  
5:  namespace EventManagement  
6:  {  
7:    public class Program  
8:    {  
9:      public static void Main(string[] args)  
10:      {  
11:        Log.Logger = new LoggerConfiguration()  
12:          .Enrich.FromLogContext()  
13:          .MinimumLevel.Debug()  
14:          .WriteTo.ColoredConsole(  
15:            LogEventLevel.Verbose,  
16:            "{NewLine}{Timestamp:HH:mm:ss} [{Level}] ({CorrelationToken}) {Message}{NewLine}{Exception}")  
17:    .WriteTo.File("log.txt")  //Create a seprate file for logging
18:            .CreateLogger();  
19:        try  
20:        {  
21:          CreateWebHostBuilder(args).Build().Run();  
22:        }  
23:        finally  
24:        {  
25:          Log.CloseAndFlush();  
26:        }  
27:      }  
28:      public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>  
29:        WebHost.CreateDefaultBuilder(args)  
30:          .UseSerilog()  
31:          .UseStartup<Startup>();  
32:    }  
33:  }  
  • Add the Logger into your Controller or Service, here EventName is the Model Class.
1:  using System;  
2:  using System.Collections.Generic;  
3:  using System.Diagnostics;  
4:  using System.Linq;  
5:  using System.Threading.Tasks;  
6:  using EventManagement.Models;  
7:  using Microsoft.AspNetCore.Mvc;  
8:  using Microsoft.Extensions.Logging;  
9:  namespace EventManagement.Controllers  
10:  {  
11:    public class HomeController : Controller  
12:    {  
13:      ILogger<HomeController> logger;  
14:      public HomeController(ILogger<HomeController> logger)  
15:      {  
16:        this.logger = logger;  
17:      }  
18:      public IActionResult Index()  
19:      {  
20:        this.logger.LogDebug("Index was called");  
21:        return View();  
22:      }  
23:      [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]  
24:      public IActionResult Error()  
25:      {  
26:        return View(new Event { EventName = Activity.Current?.Id ?? HttpContext.TraceIdentifier });  
27:      }  
28:    }  
29:  }  
  • Add the Following Code in your Model Class:
 //RequestId is a Entity in Model Class  
 public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);  

Now, All set Run your Program log.txt file will be created and Logging will also be displayed in Console and Developer will be able to easily diagnose the Code.

0 Comments:

Post a Comment