[ASP.NET] Setting Up NLog in ASP.NET Core
발행일: Feb, 2025
조회수: 0
단어수: 78
Table of Contents
Installing NLog.Web.AspNetCore
Search for NLog.Web.AspNetCore in the NuGet Package Manager and install it.

Alternatively, add the following line to your project file:
<PackageReference Include="NLog.Web.AspNetCore" Version="5.2.1" />
Configuring Program.cs
Add the following code to Program.cs:
using NLog.Web;
...
// NLog
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(LogLevel.Trace);
builder.Host.UseNLog();
...
var app = builder.Build();
Creating NLog.config
Create an NLog.config file with the following content:
<?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="Info"
internalLogFile="c:\temp\internal-nlog-AspNetCore.txt">
<variable name="logFilePath" value="./Logs/MyApp.${shortdate}.log" />
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets>
<target xsi:type="File"
name="logfile"
fileName="${logFilePath}"
layout="${longdate} - LEVEL=${level:upperCase=true}: ${message}"
keepFileOpen="true"
encoding="utf-8"
archiveAboveSize="10000000"
archiveNumbering="DateAndSequence"
archiveDateFormat="yyyy-MM-dd" />
<target xsi:type="Console"
name="console"
layout="${longdate} - LEVEL=${level:upperCase=true}: ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logfile" />
<logger name="*" minlevel="Debug" writeTo="console" />
</rules>
</nlog>
Using ILogger with NLog
Once configured, all logs using the ILogger interface will be redirected to NLog. You can use either NLog's logging functions or the ILogger interface methods.
public ILogger Logger { get; }
public NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Logger.LogInformation("Log message from ILogger");
logger.Info("Log message from NLog");
}
