.NET Core使用Nlog记录日志
1.引入Nuget包
Nlog
Nlog.Web.AspNetCore
2.添加nlog配置文件
1 <?xml version="1.0" encoding="utf-8" ?> 2 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 autoReload="true" 5 internalLogLevel="Warn" 6 internalLogFile="internal-nlog.txt"> 7 <!--define various log targets--> 8 <targets> 9 <!--write logs to file--> 10 <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log" 11 layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> 12 13 <target xsi:type="File" name="ownFile-web" fileName="nlog-my-${shortdate}.log" 14 layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> 15 <target xsi:type="Null" name="blackhole" /> 16 </targets> 17 <rules> 18 <!--All logs, including from Microsoft--> 19 <logger name="*" minlevel="Trace" writeTo="allfile" /> 20 21 <!--Skip Microsoft logs and so log only own logs--> 22 <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> 23 <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> 24 </rules> 25 </nlog>
3.在StartUp.cs中配置nlog
1 public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory) 2 { 3 app.UseStaticFiles(); 4 //使用NLog作为日志记录工具 5 loggerFactory.AddNLog(); 6 //引入Nlog配置文件 7 env.ConfigureNLog("nlog.config"); 8 if (env.IsDevelopment()) 9 { 10 app.UseDeveloperExceptionPage(); 11 } 12 app.UseMvc(); 13 }
4.在程序中中使用nlog写日志
下面是注入到控制器中的示例
1 public class ValuesController : Controller 2 { 3 4 private ILogger<ValuesController> logger; 5 public ValuesController(ILogger<ValuesController> _logger) 6 { 7 logger = _logger; 8 } 9 // GET api/values 10 [HttpGet] 11 public string Get() 12 { 13 logger.LogError("123"); 14 return "value"; 15 }
调用该api,然后查看文件目录
5.日志文件生成在指定目录下
大家会发现文件是生成在项目目录下的,日志多的时候,会导致文件目录太乱
此时,只需更改nlog.config中的内容如下即可生成在logs目录里
<targets> <!--write logs to file--> <target xsi:type="File" name="allfile" fileName="logs/all/nlog-all-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="File" name="ownFile-web" fileName="logs/my/nlog-my-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="Null" name="blackhole" /> </targets>