1、安裝NuGet包
運行:Install-Package NLog.Web.AspNetCore
運行:Install-Package NLog
在csproj中編輯:
<PackageReference Include="NLog" Version="4.5.3" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.5.3" />
2、創建一個nlog.config文件。

<?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" throwConfigExceptions="true" internalLogLevel="info" internalLogFile="D:\temp\internal-nlog.txt"> <!-- 要寫的目標--> <targets> <!--將日志寫入文件 --> <target xsi:type="File" name="allfile" fileName="D:\temp\nlog-all-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" /> <!-- 啟用asp.net核心布局渲染器 --> <target xsi:type="File" name="ownFile-web" fileName="D:\temp\nlog-own-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" /> </targets> <!-- 從記錄器名稱映射到目標的規則 --> <rules> <!--所有的記錄,包括從微軟--> <logger name="*" minlevel="Trace" writeTo="allfile" /> <!--跳過非關鍵微軟日志,因此只記錄自己的日志--> <logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole --> <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> </rules> </nlog>
3、在csproj
手動編輯文件並添加
<ItemGroup> <Content Update="nlog.config" CopyToOutputDirectory="Always" /> </ItemGroup>
4、更新program.cs

public static void Main(string[] args) { // NLog:首先設置記錄器以捕獲所有錯誤 var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { logger.Debug("init main"); BuildWebHost(args).Run(); } catch (Exception exception) { // NLog:catch安裝錯誤 logger.Error(exception, "Stopped program because of exception"); throw; } finally { //確保在退出應用程序之前刷新並停止內部定時器/線程(避免Linux上的分段錯誤) NLog.LogManager.Shutdown(); } } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }) .UseNLog() // NLog:setup NLog用於依賴注入 .Build();
5、配置appsettings.json

{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning", "Microsoft": "Information" } } }
6、寫日志

private readonly ILogger _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; _logger.LogDebug(1, "NLog injected into HomeController"); } public IActionResult Index() { _logger.LogInformation("Hello, this is the index!"); return View(); }
7、輸出示例
