How to use NLog in ASP .Net 8?

 NLog is a popular logging framework for .NET applications. It offers advanced features like configurable log levels, multiple targets (e.g., files, databases, consoles), and flexible configuration options. To use NLog in an ASP.NET 8 application, you need to follow these steps:

1. Install NLog and NLog.Extensions.Logging Packages

First, you need to add the necessary NuGet packages to your project.

  1. Add NLog and related packages:

    bash

    dotnet add package NLog dotnet add package NLog.Web.AspNetCore dotnet add package NLog.Extensions.Logging
    • NLog: Core NLog functionality.
    • NLog.Web.AspNetCore: Integration with ASP.NET Core.
    • NLog.Extensions.Logging: Integration with ASP.NET Core's built-in logging system.

2. Configure NLog

NLog can be configured either via code or configuration files. Here, we’ll use a configuration file for simplicity.

  1. Create nlog.config File:

    Create a file named nlog.config in the root of your project with the following content:

    xml

    <?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"> <targets> <!-- File target --> <target name="file" xsi:type="File" fileName="logs/logfile.txt" layout="${longdate}|${level:uppercase=true}|${logger}|${message} ${exception}" /> <!-- Console target --> <target name="console" xsi:type="Console" layout="${longdate}|${level:uppercase=true}|${logger}|${message} ${exception}" /> </targets> <rules> <!-- Log to file and console --> <logger name="*" minlevel="Info" writeTo="file,console" /> </rules> </nlog>

    This configuration defines two targets: a file and the console. All logs with level Info or higher are written to both targets.

  2. Configure NLog in Program.cs or Startup.cs:

    Update your Program.cs to integrate NLog with the ASP.NET Core logging system:

    csharp

    using NLog; using NLog.Web; var builder = WebApplication.CreateBuilder(args); // Set up NLog configuration var logger = LogManager.LoadConfiguration("nlog.config").GetCurrentClassLogger(); builder.Logging.ClearProviders(); // Remove default logging providers builder.Logging.SetMinimumLevel(LogLevel.Trace); // Set minimum log level builder.Host.UseNLog(); // Use NLog for logging var app = builder.Build(); try { logger.Info("Application starting..."); app.Run(); } catch (Exception ex) { logger.Error(ex, "Application stopped due to an exception"); throw; } finally { LogManager.Shutdown(); // Ensure to flush and close down NLog }
    • LogManager.LoadConfiguration("nlog.config"): Loads the NLog configuration from the nlog.config file.
    • builder.Logging.ClearProviders(): Removes the default logging providers (e.g., Console, Debug) so that NLog can be the primary logger.
    • builder.Host.UseNLog(): Configures the application to use NLog as the logging provider.

3. Using NLog in Your Application

  1. Inject Logger into Controllers or Services:

    Inject ILogger<T> into your controllers or services and use it as needed:

    csharp

    using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { _logger.LogInformation("Index page visited."); return View(); } }
  2. Log Messages in Your Application:

    Use the ILogger instance to log messages at different levels:

    csharp

    _logger.LogTrace("Trace message"); _logger.LogDebug("Debug message"); _logger.LogInformation("Information message"); _logger.LogWarning("Warning message"); _logger.LogError("Error message"); _logger.LogCritical("Critical message");

4. Additional Configuration

You can add more sophisticated configurations to nlog.config, such as:

  • Asynchronous Logging: Improve performance by adding async targets.
  • Different Log Levels: Customize logging for specific parts of your application.
  • Log File Management: Use file archiving and rolling policies to manage log files.

Example of Asynchronous Logging and File Rolling:

xml

<targets> <!-- Asynchronous file target with rolling --> <target name="file" xsi:type="File" fileName="logs/logfile.txt" layout="${longdate}|${level:uppercase=true}|${logger}|${message} ${exception}"> <archive fileName="logs/logfile.{#}.txt" archiveEvery="Day" /> </target> <!-- Console target --> <target name="console" xsi:type="Console" layout="${longdate}|${level:uppercase=true}|${logger}|${message} ${exception}" /> </targets> <rules> <logger name="*" minlevel="Info" writeTo="file,console" /> </rules>

Summary

  1. Install Packages: Add NLog and related packages.
  2. Configure NLog: Create and configure nlog.config.
  3. Integrate with ASP.NET Core: Update Program.cs to use NLog.
  4. Log Messages: Inject and use ILogger in your controllers or services.
  5. Additional Features: Customize NLog configuration for performance and file management.

By following these steps, you can effectively integrate NLog into your ASP.NET 8 application, providing advanced logging capabilities that are crucial for monitoring and debugging your application.

Post a Comment