Sunday, 27 September 2020

ASP.NET Core - Logging

 .NET Core supports a logging API that works with a variety of built-in and third-party logging providers. This article shows how to use the logging API with built-in providers.

Logging providers

Logging providers store logs, except for the Console provider which displays logs. For example, the Azure Application Insights provider stores logs in Azure Application Insights. Multiple providers can be enabled

Add Logging Providers

In the ASP.NET Core MVC application, the call to the WebHost.CreateDefaultBuilder(args) method in the Program.cs internally adds the following logging providers.

  1. Console
  2. Debug
  3. EventSource 

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
               .UseStartup<Startup>();
}

Look at the source code of the WebHost.CreateDefaultBuilder() method on GitHub and you will find the following code:

.ConfigureLogging((hostingContextlogging=>
    {
        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
        logging.AddConsole();
        logging.AddDebug();
        logging.AddEventSourceLogger();
    }).

Thus, if you want to use these providers, no need to add them manually. If you want to override the  existing log providers or any default provider, then you need to remove all the existing providers and add the provider of your choice. To configure logging providers, call the ConfigureLogging() extension method of IWebHostBuilder, as shown below.

public static IWebHostBuilder CreateWebHostBuilder(string[] args=>
    WebHost.CreateDefaultBuilder(args)
    .ConfigureLogging(logBuilder =>
    {
        logBuilder.ClearProviders(); // removes all providers from LoggerFactory
        logBuilder.AddConsole();  

        // Add Trace listener provider
        logBuilder.AddTraceSource("Information, ActivityTracing"); 
    })
.UseStartup<Startup>();

You can also configure the logging provider using ILoggerFactory in the Configure() method of the Startup class. Let's see an example on how to store logs in a text file.

Store Logs in a Text File 

To store logs in a file, install the NuGet package Serilog.Extensions.Logging.File. Serillog includes an extension method for ILoggerFactory but not for ILogBuilder (in v 1.1.0). So, go to the Startup.cs file and add the ILoggerFactory parameter in the Configure() method. Then, call the AddFile() extension method to add Serillog file provider, as shown below. ASP.NET Core dependency injection will automatically pass an instance of the LoggerFactory for this parameter.

public void Configure(IApplicationBuilder appIHostingEnvironment env,
ILoggerFactory loggerFactory
{
    // other code remove for clarity 
    loggerFactory.AddFile("Logs/errorlog-{Date}.txt");
}

This will store all the logs in the errorlog-<date>.txt file, under the Logs folder in your application.

Create Logs in the Controller

We can use ILogger or ILoggerFactory anywhere in an application using ASP.NET Core DI (Dependency Injection). Consider the following example of HomeController:

namespace AspDotNetCoreMvcApp.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger _logger;

        public HomeController(ILogger<HomeControllerlogger){
            _logger = logger;
        }
        
        public IActionResult Index()
        {
            _logger.LogInformation("Log message in the Index() method");

            return View();
        }

        public IActionResult About()
        {
            _logger.LogInformation("Log message in the About() method");
            
            return View();
        }
    }
}

In the above example, the ILogger<HomeController> parameter is included in the constructor. ASP.NET Core DI will pass the ILogger instance, which can be used to log in the Index() and About() action methods.

Passing HomeController as generic type for the ILogger<HomeController>, will be used as a category. For example, specifying ILogger<HomeController> will display a fully qualified name AspDotNetCoreMvcApp.Controllers.HomeController in the logs, as shown below.

infoAspDoteNetCoreMvcApp.Controllers.HomeController[0]
Log message in the Index() method

Let's understand the above log message. Here, we logged information using the LogInformation() method, so it starts with "info:" followed by the fully qualified name of the class where a log is created: AspDoteNetCoreMvcApp.Controllers.HomeController[0]. [0] is the event id. You can specify this event id to identify a record, e.g. Id, page number or other important information which uniquely identifies a log. We didn't specify any event id, so it will be 0. The next line is an actual log message: "Log message in the Index() method".

The same can be achieved by passing ILoggerFactory in the constructor.

public class HomeController : Controller
{
    private readonly ILogger _logger;

    public HomeController(ILoggerFactory logFactory
    {
        _logger = logFactory.CreateLogger<HomeController>();
    }
        
    public IActionResult Index()
    {
        _logger.LogInformation("Log message in the Index() method");

        return View();
    }
}

You will get same logging information. Thus, we can implement logging in ASP.NET Core MVC application.

Refrence: https://docs.microsoft.comhttps://www.tutorialsteacher.com/

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives