Popular Posts

July 07, 2024

Explain the Logging system in .NET Core and ASP.NET Core

 

The logging system in .NET Core and ASP.NET Core provides a robust framework for logging information from applications. It supports a variety of logging providers and allows developers to log messages in a structured and extensible way. Here’s an overview of how the logging system works and how you can configure and use it:

1. Setting Up Logging

Logging is typically configured in the Program.cs and Startup.cs files. By default, .NET Core applications include logging during the setup process.

Example in Program.cs:

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.AddConsole();
                logging.AddDebug();
                logging.AddEventSourceLogger();
            });
}
Explain the Logging system in .NET Core and ASP.NET Core


2. Configuring Logging Providers

ASP.NET Core supports various logging providers, including:

  • Console
  • Debug
  • EventSource
  • EventLog (Windows only)
  • TraceSource
  • Azure App Services
  • Application Insights

You can configure these providers in Program.cs or Startup.cs.

3. Logging Levels

Logging levels determine the severity of the logs. ASP.NET Core defines the following levels, from most verbose to least verbose:

  • Trace
  • Debug
  • Information
  • Warning
  • Error
  • Critical
  • None (used to disable logging)

You can set the logging level for each provider in the appsettings.json file:

{

  "Logging": {

    "LogLevel": {

      "Default": "Information",

      "Microsoft": "Warning",

      "Microsoft.Hosting.Lifetime": "Information"

    },

    "Console": {

      "LogLevel": {

        "Default": "Debug"

      }

    }

  }

}

4. Creating and Using Loggers

You can inject the ILogger<T> service into your classes to create log entries. For example:

public class HomeController : Controller

{

    private readonly ILogger<HomeController> _logger;


    public HomeController(ILogger<HomeController> logger)

    {

        _logger = logger;

    }


    public IActionResult Index()

    {

        _logger.LogInformation("Executing Index action.");

        return View();

    }


    public IActionResult Privacy()

    {

        _logger.LogError("An error occurred in the Privacy action.");

        return View();

    }

}

5. Logging Scopes

Logging scopes are useful for grouping related log entries together. Scopes can be used to include contextual information across multiple log entries:

public IActionResult Index()

{

    using (_logger.BeginScope("ScopeId: {ScopeId}", Guid.NewGuid()))

    {

        _logger.LogInformation("Inside the scope.");

        // Other log entries

    }

    return View();

}

6. Custom Logging Providers

You can create custom logging providers by implementing the ILoggerProvider and ILogger interfaces. This allows you to direct log output to custom destinations, such as a database or an external service.

7. Structured Logging

ASP.NET Core supports structured logging, where you can log messages with named placeholders. This allows for more detailed and searchable log entries:

_logger.LogInformation("User {UserId} accessed {Page}", userId, pageName);

Example Configuration in Startup.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

        logger.LogInformation("Application started.");
    }
}

Summary

The logging system in .NET Core and ASP.NET Core is highly configurable and extensible, allowing you to log messages to various destinations and at different levels of severity. By understanding and leveraging this system, you can gain valuable insights into your application's behavior and troubleshoot issues more effectively.


No comments:
Write comments