1. 程式人生 > >.NET Core使用Nlog記錄日誌

.NET Core使用Nlog記錄日誌

microsoft except urn odin conf -c lena 註入 eight

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.使用nlog

在StartUp.cs中配置配置日誌中間件

 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>

.NET Core使用Nlog記錄日誌