1. Installing the NLog Packages
Add the following NuGet packages to your project:
NLogNLog.Web.AspNetCore
These can be installed via the Package Manager Console or the .NET CLI.
2. Configuring NLog
Create an NLog.config XML file in the project root. Set its Build Action to Content and Copy to Output Directory to Copy if newer. Below is a sample configuration with explanations:
<?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"
autoReload="true"
internalLogLevel="Off"
internalLogFile="log/nlog.txt">
<targets async="true">
<target xsi:type="File" name="allfile" fileName="${basedir}/logs/log.txt"
enableFileDelete="true"
maxArchiveFiles="20"
concurrentWrites="true"
archiveNumbering="Sequence"
archiveAboveSize="2097152"
keepFileOpen="true"
openFileCacheTimeout="30"
autoFlush="false"
createDirs="true"
encoding="utf-8"
enableArchiveFileCompression="true"
archiveFileName="${basedir}/archivelogs/log${date:format=yyyy-MM-dd_HH-mm-ss}.zip"
layout="[${counter}] ${longdate} [${level}] [${processid}] [${processname}] ${message} ${newline} ${stacktrace}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="allfile"/>
</rules>
</nlog>
Configuration Notes
archiveAboveSize: Files larger then this value (in bytes) are automatically archived.keepFileOpen: Keeps the file open to improve write performance.autoFlush: Whenfalse, the buffer is flushed periodically, reducing disk I/O.enableArchiveFileCompression: Archived file are compressed into ZIP format.- The
layoutstring defines the format of each log entry.
3. Registering NLog in the Application
Configure NLog in Program.cs before building the host. Use the UseNLog() extension method on IHostBuilder.
public class Program
{
public static void Main(string[] args)
{
var configPath = Path.Combine("Config", "NLog.config");
var logger = NLogBuilder.ConfigureNLog(configPath).GetCurrentClassLogger();
try
{
logger.Debug("Application starting.");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
logger.Error(ex, "Application terminated due to an exception.");
throw;
}
finally
{
logger.Debug("Application shutting down.");
NLog.LogManager.Shutdown();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
})
.UseNLog();
}
Important: Place
NLog.configin a subfolder (e.g.,Config/) or adjust the path accordingly. Ensure theLogManager.Shutdown()call in thefinallyblock to flush logs and release resources.
4. Using NLog in Controllers
After registration, you can inject ILogger<T> into your controllers as usual. No additional changes are required.
[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IActionResult Get()
{
_logger.LogInformation("Fetching weather forecast data.");
// ... logic
return Ok();
}
}
The NLog framwork automatically captures logs from all dependencies, including ASP.NET Core internal loggers, according to the configured rules.