net-core
  1. net-core-configure-and-use-logging

Configure and Use Logging in ASP.NET Core

ASP.NET Core includes a built-in logging API that provides a way to log messages from an application. These logs can help developers understand how the application is behaving, find errors and issues, and monitor the application's performance.

In this page, we will discuss how to configure and use logging in an ASP.NET Core application.

Configuration

ASP.NET Core provides several built-in logging providers that allow you to log messages to different targets, such as text files, the console, or a logging database. You can configure the logging providers using the ConfigureLogging method in your Startup class.

Here is an example of how to configure logging to log messages to a console:

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, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();
    
        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?}");
        });
    }
}

Logging API

The Logging API in ASP.NET Core includes several methods that allow you to log messages with different severity levels. These severity levels include:

  • Trace
  • Debug
  • Information
  • Warning
  • Error
  • Critical

Here is an example of how to use the Logging API to log an error message:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        try
        {
            // Code that may throw an exception
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An error occurred.");
        }

        return View();
    }
}

Output

The output of logging is determined by the logging provider that is configured for your application. For example, if you configure your application to log messages to a file, you can find the log file in the specified location with all the log data.

Explanation

Logging is an essential part of any application. It helps the developers and operations team keep a close watch on the application's behavior, find problems, and resolve them timely. ASP.NET Core provides a built-in logging API that can help developers log messages with various severity levels and to different targets.

Use

Developers and operations teams can use logging to track the application's health, track potential issues, and optimize application performance. As it is flexible in configurations, it is a valuable tool for production applications.

Important Points

  • ASP.NET Core includes built-in logging providers that can help log messages to different targets.
  • The Logging API includes various severity levels that allow you to log messages from Trace to Critical.
  • Logging is essential for identifying potential issues in an application and optimizing its performance.

Summary

ASP.NET Core's built-in logging API provides a flexible way to log messages from an application. This page discussed how to configure and use the logging API in an ASP.NET Core application. Developers and operations teams should use logging to track the application's performance, detect potential issues, and optimize its performance.

Published on: