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" />
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();
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>
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");
}
ยฉ 2025 juniyunapapa@gmail.com.