.Net Core使用NLog记录日志
参见:https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2
补充:
如在本地能写log,但是发布到IIS无法写log,请注意引用程序池的账号,默认的“ApplicationPoolIdentity”应该是没有权限的,将其改为“LocalSystem”即可。
大致步骤:
- Nuget中引用NLog及NLog.Web.AspNetCore 4.5+
- 创建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" internalLogLevel="info" internalLogFile="logs\internal-nlog.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 name="allFile" xsi:type="File" fileName="logs\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 name="ownFile" xsi:type="File" fileName="logs\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}" /> <target name="blackHole" xsi:type="Null" /> </targets> <!-- rules to map from logger name to target --> <rules> <!--All logs, including from Microsoft--> <logger name="*" minlevel="Trace" writeTo="allFile" /> <!--Own logs--> <logger name="HiP.*" minlevel="Trace" writeTo="ownFile" /> <!--Skip non-critical Microsoft logs and so log only own logs--> <!--<logger name="Microsoft.*" maxLevel="Info" writeTo="blackHole" final="true" />--> </rules> </nlog> <!--LogLevel="Trace|Debug|Info|Warn|Error|Fatal"-->
- 右键nlog.config,属性,生成操作设为“内容”,复制到输出目录为“始终复制”
- Program.cs中:
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 ex) { //NLog: catch setup errors logger.Error(ex, "Stopped program because of exception"); throw ex; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) //会调用Startup中的ConfigureContainer方法 .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseStartup<Startup>() .UseUrls("http://localhost:8080") //这里是配置log的 .ConfigureLogging((hostingContext, builder) => { builder.ClearProviders(); //builder.SetMinimumLevel(LogLevel.Warning); //使用Nlogs的配置 //builder.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); //builder.AddConsole(); //builder.AddDebug(); }) .UseNLog(); // NLog: setup NLog for Dependency injection. 3.0中这样添加 }); }
- 配置appsettings.json。注意在配置中的设置将覆盖代码中的SetMinimumLevel属性。所以要么删除“Default”使用代码中的配置,要么就要设置正确。
{ "Logging": { "LogLevel": { "Default": "Trace", "Microsoft": "Information" } } }
注意:如你有多个环境,注意appsetings.Development.json的配置。
- 使用:
using Microsoft.Extensions.Logging; public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { _logger.LogInformation("Index page says hello"); return View(); }
- 结果查看。如你的配置与我一致,则在项目的logs文件夹会存在internal-nlog.txt文件。在bin\Debug\netcoreappXX\logs目录下会以日期存在输出日志。