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


1、先創建 .net core Web 應用程序,選擇API

 

 

 

 

 

 

2、安裝 Nuget 包:Nlog.Web.AspNetCore

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

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

3、添加配置文件: nlog.config  

 

 注意,此處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="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"
    }
  }

4、注冊日志依賴

方法一:通過修改Program.cs

//需引用
//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函數

//需引用
//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

5、修改 Controller, 輸出日志:

 

  [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日志");//直接調內置的級別函數

6、結果

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

internal-nlog 記錄了NLog的啟動及加載config的信息。
nlog-all 記錄了所有日志
nlog-own 記錄了我們自定義的日志

 7、修改配置

 打開官方提供的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

 




 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM