Logging file using NLog in ASP.NET Core

By FoxLearn 1/2/2025 3:12:01 AM   8.6K
Integrating NLog into an ASP.NET Core application is a straightforward process.

NLog is a powerful and flexible logging framework, and it can be used alongside or instead of the built-in logging providers in ASP.NET Core.

Follow these steps to set up NLog in your ASP.NET Core project:

1. Install NLog NuGet Packages

Right-clicking on your project, then select Manage Nuget Packages. Next, Search for 'NLog', then install 'NLog.Schema', 'NLog.Config', 'NLog.Extensions.Logging', 'NLog.Web.AspNetCore' to your project.

nlog asp.net core

After you finish installing the NLog library, you can find NLog.config in your project.

2. Configure NLog

Right-clicking on NLog.config file, then select Properties => set Copy to Output Directory to Copy if newer

nlog.config

Opening your NLog.config file, then modify your configuration as shown below.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="true"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

    <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
    <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Skip non-critical Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" maxlevel="Info" final="true" />
    <!-- BlackHole without writeTo -->
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

In this configuration:

  • Logs are written to both the console and a file (logs will be saved with the current date in the filename).
  • Log entries with a minimum level of Info will be logged to both targets.

Creating a Temp folder in your C:\ disk, and don't forget to set the permissions to read and write.

3. Set Up NLog

Update Program.cs for ASP.NET Core 3.x or earlier

For earlier versions of ASP.NET Core, you can configure NLog in the Startup.cs file like this:

public static void Main(string[] args)
{
    var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    try
    {
        logger.Debug("init main");
        CreateHostBuilder(args).Build().Run();
    }
    catch (Exception exception)
    {
        //NLog: catch setup errors
        logger.Error(exception, "Stopped program because of exception");
        throw;
    }
    finally
    {
        // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
        NLog.LogManager.Shutdown();
    }
}

and don't forget to modify the CreateHostBuilder method allows you to use NLog.

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
      .ConfigureWebHostDefaults(webBuilder =>
      {
          webBuilder.UseStartup<Startup>();
      })
      .ConfigureLogging(logging =>
      {
          logging.ClearProviders();
          logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
      })
      .UseNLog();  // NLog: Setup NLog for Dependency injection

You can also modify your CreateHostBuilder method as shown below.

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddDebug();
                logging.AddNLog();
                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

If you get an error

ILoggingBuilder' does not contain a definition for 'AddNLog' and no extension method 'AddNLog' accepting a first argument of type 'ILoggingBuilder'.

You should add the NLog.Extension.Logging to your Program.cs or Startup.cs

using NLog.Extensions.Logging;

For ASP.NET Core 6+

ASP.NET Core uses the Program.cs file to configure the application. Modify this file to use NLog.

using Microsoft.Extensions.Hosting;
using NLog;
using NLog.Web;

var builder = WebApplication.CreateBuilder(args);

// Configure NLog as the logging provider
builder.Logging.ClearProviders();  // Remove other loggers (optional)
builder.Logging.SetMinimumLevel(LogLevel.Trace); // Optional: Set the minimum level for logging
builder.Host.UseNLog();  // Integrates NLog

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Use the default NLog exception handler middleware
app.UseExceptionHandler("/Home/Error");

app.UseStaticFiles();

app.UseRouting();

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

app.Run();

4. Use NLog

Opening HomeController, then modify your Index action as shown below.

public IActionResult Index()
{
    _logger.LogInformation("NLog Info logging...");
    return View();
}

Running your project, then you can see log file in the temp directory.

logging file using nlog

By following the above steps, NLog is now integrated with your ASP.NET Core application, and you can log messages to various outputs (console, file, etc.).