.net core 2.1 Nlog.Web.AspNetCore Nlog日誌

一、先建立 .net core Web 應用程序,選擇APIgit

 

 

 

 

 

 

二、安裝 Nuget 包:Nlog.Web.AspNetCoregithub

install-package Nlog
install-package Nlog.Web.AspNetCore

或者打開Nuget管理界面搜索Nlog.Web.AspNetCore(我安裝的版本是V4.9.0)web

三、添加配置文件: nlog.config  json

 

 注意,此處nlog.config最好是小寫的,需修改屬性使其始終複製api

<?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="c:\temp\internal-nlog.txt">

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target xsi:type="File" name="allfile" fileName="c:\temp\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 xsi:type="File" name="ownFile-web" fileName="c:\temp\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}" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Skip non-critical Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo -->
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>
nlog.config(來源:官方文檔)

配置appsettings.json

 "Logging": {
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Information"
    }
  }

四、註冊日誌依賴mvc

方法一:經過修改Program.csapp

//需引用
//using Microsoft.Extensions.Logging;
//using NLog.Web;
 
public class Program
    {
        public static void Main(string[] args)
        {
            NLog.Web.NLogBuilder.ConfigureNLog("nlog.config");
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .ConfigureLogging(logging =>
                 {
                     logging.ClearProviders(); //移除已經註冊的其餘日誌處理程序
                     logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); //設置最小的日誌級別
                 })
                 .UseNLog();
    }
Program.cs

方法二:經過修改Startup.cs裏的Configure函數asp.net

//需引用
//using NLog.Extensions.Logging;
//using NLog.Web;

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            loggerFactory.AddNLog();//添加NLog
            env.ConfigureNLog("nlog.config");//讀取Nlog配置文件

          
            app.UseMvc();
        }
Configure

五、修改 Controller, 輸出日誌:ide

 

  [Route("api/")]
    public class LoginController : Controller
    {
        private ILogger<LoginController> logger;
         public LoginController(ILogger<LoginController> _logger)
        {
             logger = _logger;
          }


        [Route("Login")]
        [HttpGet]
        public stringLogin()
        {
            logger.LogInformation("Info日誌");
            logger.LogError("Error日誌");
            logger.LogWarning("Warning日誌");
            logger.LogCritical("Critical日誌");
            logger.LogWarning("Warning日誌");
            logger.LogTrace("Trace日誌");
            logger.Log(LogLevel.Warning, "LogWarn日誌");
            logger.Log(LogLevel.Debug, "LogDebug日誌");
            logger.Log(LogLevel.Error, "LogError日誌");
            return "";
        }
}     
控制器

 

打印日誌的時候有兩種方式函數

 logger.Log(LogLevel.Warning, "LogWarning日誌:"); //標紅的地方能夠選擇日誌的級別 

 logger.LogWarning("Warning日誌");//直接調內置的級別函數

六、結果

 程序跑起來以後會出現前兩個文件~訪問完接口後會出現最後那個文件

internal-nlog 記錄了NLog的啓動及加載config的信息。
nlog-all 記錄了全部日誌
nlog-own 記錄了咱們自定義的日誌

 七、修改配置

 打開官方提供的nlog.config  配置參考 https://github.com/NLog/NLog/wiki/Configuration-file

子節點<target>  配置參考 https://nlog-project.org/config/?tab=targets

屬性Layout表示輸出文本格式 配置參考 https://nlog-project.org/config/?tab=layouts

子節點<rule>  日誌的路由表  順序是從上往下 一個<logger>就是一個路由信息

日誌級別:Trace >Debug> Information >Warn> Error> Fatal
<logger>屬性:
name - 日誌源/記錄者的名字 (容許使用通配符*) minlevel 匹配日誌範圍的最低級別 maxlevel : 匹配日誌範圍的最高級別 level : 單一日誌級別 levels : 一系列日誌級別,由逗號分隔 writeTo : 日誌應該被寫入的目標,由逗號分隔,與target的你name對應 final : 爲true標記當前規則爲最後一個規則。其後的logger不會運行

附最後的配置文檔

<?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"
    >


  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target xsi:type="File" name="allfile" fileName="log\${shortdate}-All.log"
            layout="${longdate} | ${event-properties:item=EventId_Id:whenEmpty=0} | ${uppercase:${level}}|${logger} |${message} ${exception:format=tostring}" />

    <!-- another file log, only own logs.Uses some ASP.NET core renderers -->
    <target xsi:type="File" name="errorfile" fileName="log\${shortdate}-Error.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}" />

    <target xsi:type="File" name="taskfile" fileName="log\${shortdate}-Warn.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}" />

    <target xsi:type="File" name="runfile" fileName="log\${shortdate}-Info.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 to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name = "*" minlevel="Trace" writeTo="allfile" />
    <!--Skip non-critical Microsoft logs and so log only own logs-->
    <logger name = "*" levels="Error,Warn,Critical" writeTo="errorfile" />
    <logger name = "*" level="Info" writeTo="taskfile" />
    <logger name = "*" level="Warn" writeTo="runfile" final="true"/>

  </rules>
</nlog>
nlog.config

 

參考github: https://github.com/nlog/nlog/wiki

相關文章
相關標籤/搜索