DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

N-Log Implementation In Asp.net core Web API

To implement N-Log in an ASP.NET Core Web API, you can follow these steps:

Step 1: Install NLog Package
Start by installing the NLog package in your ASP.NET Core Web API project. You can do this using the NuGet Package Manager or by adding the package reference manually to your project file.

Step 2: Configure NLog
Next, you need to configure NLog to define where and how the logs should be stored. You can do this by adding an nlog.config file to your project or by configuring NLog programmatically in your code. Here's an example of configuring NLog programmatically in the Program.cs file:

using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;

public class Program
{
    public static void Main(string[] args)
    {
        var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        try
        {
            logger.Debug("Initializing application...");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            logger.Error(ex, "An error occurred during initialization.");
            throw;
        }
        finally
        {
            NLog.LogManager.Shutdown();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            })
            .UseNLog()
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Use NLog in Controllers or Services
Once NLog is configured, you can start using it in your controllers or services to log events or exceptions. Inject an instance of ILogger<T> into your classes and use it to log messages. Here's an example of logging an informational message in a controller:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
    private readonly ILogger<MyController> _logger;

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

    [HttpGet]
    public IActionResult Get()
    {
        _logger.LogInformation("Getting data...");
        // Perform your logic here
        return Ok();
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Customize NLog Configuration (optional)
You can customize the NLog configuration to specify different log targets (e.g., file, database, email) and define log rules for different log levels. The nlog.config file allows you to specify these configurations. You can refer to the NLog documentation for detailed information on the available configuration options.

That's it! You have now implemented NLog in your ASP.NET Core Web API project. It will log messages and exceptions based on the configured rules and targets. Remember to handle any exceptions that may occur during the logging process to avoid crashing your application.

Top comments (0)