将 ASP.Net Core 提供的默认日志提供程序替换成 NLog。
添加相关依赖
1 2
| Install-Package NLog.Extensions.Logging -Pre Install-Package NLog.Web.AspNetCore
|
创建好Nlog配置文件(nlog.config)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| <?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="Warn" internalLogFile="internal-nlog.txt"> <!--define various log targets--> <targets> <!--write logs to file--> <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="File" name="ownFile-web" fileName="nlog-my-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="Null" name="blackhole" /> </targets> <rules> <!--All logs, including from Microsoft--> <logger name="*" minlevel="Trace" writeTo="allfile" /> <!--Skip Microsoft logs and so log only own logs--> <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> </rules> </nlog>
|
Startup.cs中添加使用的服务
1 2 3 4 5 6
| public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddNLog(); env.ConfigureNLog("nlog.config"); }
|
使用日志
1 2 3 4 5 6 7 8 9 10 11 12 13
| static Logger Logger = LogManager.GetCurrentClassLogger(); public IActionResult Index() { Logger.Info("普通信息日志-----------"); Logger.Debug("调试日志-----------"); Logger.Error("错误日志-----------"); Logger.Fatal("异常日志-----------"); Logger.Warn("警告日志-----------"); Logger.Trace("跟踪日志-----------"); Logger.Log(NLog.LogLevel.Warn, "Log日志------------------"); return View(); }
|