十年河東,十年河西,莫欺少年窮
學無止境,精益求精
nlog是繼log4Net後C#編程界又一顆閃亮的星,俗稱super star
1、先學會使用
1.1、新建控制檯應用程序,引入如下nuget
1、Microsoft.Extensions.Logging 2、Microsoft.Extensions.Logging.Console 3、NLog.Extensions.Logging
1.2、引入nlog配置文件
首先項目中新建nlog.config文件,並將nlog.config文件屬性設置爲如果始終複製
nlog的配置文件在nlog的官網上可以下載,我們先打開nuget的官網:https://www.nuget.org/ , 搜索nlog組件
找到nlog官網鏈接
在打開的網址:https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-5 中找到nlog的配置文件內容
將內容複製到新建的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="internal-nlog-AspNetCore.txt"> <!-- enable asp.net core layout renderers --> <extensions> <add assembly="NLog.Web.AspNetCore"/> </extensions> <!-- the targets to write to --> <targets> <!-- File Target for all log messages with basic details --> <target xsi:type="File" name="allfile" fileName="logs/log-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" archiveAboveSize="10000" maxArchiveFiles="3"/> <!-- File Target for own log messages with extra web details using some ASP.NET core renderers --> <target xsi:type="File" name="ownFile-web" fileName="nlog-AspNetCore-own-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" archiveAboveSize="10000" maxArchiveFiles="3" /> <!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection --> <target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" /> </targets> <!-- rules to map from logger name to target --> <rules> <!--All logs, including from Microsoft--> <logger name="*" minlevel="Trace" writeTo="allfile" /> <!--Output hosting lifetime messages to console target for faster startup detection --> <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" /> <!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) --> <logger name="Microsoft.*" maxlevel="Info" final="true" /> <logger name="System.Net.Http.*" maxlevel="Info" final="true" /> <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> </rules> </nlog>
控制檯程序如下:
using System; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; namespace ConsoleApp1 { internal class Program { //NLog.Extensions.Logging //nuget.org //project website //找到config 新建nlog.config[名稱全小寫] 設置如果比較新則負複製 更改文本日誌存放路徑到當前程序目錄 static void Main(string[] args) { ServiceCollection services = new ServiceCollection(); services.AddLogging(log => { log.AddConsole(); log.AddNLog(); log.SetMinimumLevel(LogLevel.Information); }); services.AddScoped<LogService>(); using (ServiceProvider sp = services.BuildServiceProvider()) { var logservice = sp.GetService<LogService>(); logservice.test(); } Console.Read(); } public class LogService { private readonly ILogger<LogService> logger; public LogService(ILogger<LogService> logger) { this.logger = logger; } public void test() { for(int i = 0; i < 100000; i++) { logger.LogTrace("跟蹤"); logger.LogDebug("調試"); logger.LogInformation("信息"); logger.LogError("錯誤"); logger.LogCritical("嚴重錯誤"); try { int a = 0; int b = 1; var c = b / a; } catch (Exception ex) { logger.LogError(ex, "異常"); } } } /// <summary> /// windows 日誌 部署在linux 下無效 /// </summary> public void EventLog() { //Microsoft.Extensions.Logging.EventLog } } } }
運行此項目,可以在bin/debug/logs文件夾下看到生成的日誌文件
2、nlog配置文件解讀
NLog 配置文件是一個以 nlog
爲根節點的 XML 文件。nlog
節點可以添加命名空間,以開啓 Visual Studio 的 Intellisense 功能。
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> </nlog>
以下元素可以作爲 nlog
節點的子節點,前兩種元素在所有 NLog 配置文件中都必須存在,剩餘元素是可選的。
targets
- 定義日誌目標/輸出rules
- 定義日誌路由規則extensions
- 定義要加載的 NLog 擴展項 *.dll 文件includes
- 定義要包含的外部配置文件variables
- 設置配置變量的值
在 nlog
節點中設置屬性autoReload="true"
,NLog 會監視配置文件,並在配置文件發生更改時自動重新載入配置文件而不需要重啓應用程序。該功能支持通過 include
包含的子配置文件。示例如下,
<nlog autoReload="true"> ... </nlog>
Targets
targets
節點中定義了一系列日誌輸出目標,每一個輸出目標是一個 target
元素。對於每一個 target
元素,name
屬性和 type
屬性是必須要指定的:
name
-target
的名字。路由規則根據該屬性將日誌信息路由到當前目標。type
-target
的類型。當使用了 xsi 命名空間時,該屬性被命名爲 xsi:type。目前 NLog 支持的輸出目標列表:Targets
不同類型的 target
節點可以接受不同的屬性。例如對於 File
目標,fileName
參數指定了日誌文件的文件名;對於 Console
目標,error
參數指定日誌信息是寫到標準錯誤流還是標準輸出流。NLog 內置了許多預定義類型,也可以自定義輸出目標類型,詳見如何自定義輸出目標。
以下是 targets
節點的例子:
<targets> <target name="f1" xsi:type="File" fileName="file1${shortdate}.txt" archiveAboveSize="10000" maxArchiveFiles="3" /> <target name="f2" xsi:type="File" fileName="file2${shortdate}.txt" archiveAboveSize="10000" maxArchiveFiles="3" /> <target name="n1" xsi:type="Network" address="tcp://localhost:4001"/> <target name="ds" xsi:type="OutputDebugString"/> </targets>
archiveAboveSize 代表日誌文本文件的最大字節數,當前設定的爲 10KB
maxArchiveFiles 代表存儲的日誌文件最大個數,設置後可以避免日誌文件無限量增加,導致磁盤空間不夠
Rules
rules
節點是日誌路由規則的集合,由一個或多個 logger
元素組成。每個 logger
元素記錄了 logger 的名字、目標輸出以及要處理的日誌等級。NLog 從路由規則表的第一個 logger
開始處理,如果當前 logger
有效,則日誌信息將被輸出到指定的 target
。如果某個 logger
被標記爲 final
,那麼其後的 logger
都會被忽略。
logger
包含下列屬性:
name
- logger的名字(可以使用通配符*)minLevel
- 最小日誌等級maxLevel
- 最大日誌等級level
- 單一的日誌等級levels
- 以逗號分割的日誌等級列表writeTo
- 以逗號分割的輸出目標列表final
- 標記當前規則爲最後一條規則enabled
- 使能當前規則
如果在一條規則中定義了多個日誌等級相關的屬性(level
, levels
, minLevel
和 maxLevel
),按照優先級只生效當前優先級最高的屬性。等級相關屬性優先級如下,
level
levels
minLevel
和maxLevel
- 沒有設置(所有等級的日誌都會被記錄)
以下是 rules
節點的例子:
<rules> <logger name="Name.Space.Class1" minlevel="Debug" writeTo="f1" /> <logger name="Name.Space.Class1" levels="Debug,Error" writeTo="f1" /> <logger name="Name.Space.*" writeTo="f3,f4" /> <logger name="Name.Space.*" minlevel="Debug" maxlevel="Error" final="true" /> </rules>
final="true" 是指一旦匹配到該規則,則不繼續往下匹配,相當於for循環中的break
name ="*" 是指所有日誌都會被匹配, name 中可以指定固定的命名空間,也可以指定具有模糊匹配的命名空間
命名空間 Name.Space
下類 Class1
中高於 Debug
級別的日誌信息將被寫入輸出目標 f1
命名空間Name.Space
下類 Class1
中級別爲 Debug
和 Error
的日誌信息將被寫入 target:f1
命名空間 Name.Space
下所有類中的日誌信息將被寫入 target:f3, f4
命名空間 Name.Space
下所有類中級別在Debug
和 Error
之間 (Debug
,Info
,Warn
和 Error
) 的日誌信息不被記錄(因爲沒有指定屬性writeTo
)。由於標記了屬性 final
,之後的 logger
都會被忽略。
Extensions
extensions
節點可以添加額外的NLog元包或自定義功能,語法爲 。assembly
屬性指定的被包含程序集,配置時不用帶後綴 .dll
。示例如下,
<nlog> <extensions> <add assembly="MyAssembly" /> </extensions> <targets> <target name="a1" type="MyFirst" host="localhost" /> </targets> <rules> <logger name="*" minLevel="Info" appendTo="a1" /> </rules> </nlog>
NLog 4.0 之後,與 NLog.dll
同目錄下名如 NLog*.dll
的程序集(如 NLog.CustomTarget.dll
)會被自動加載。
Includes
include
節點指定當前配置文件包含多個子配置文件,語法爲 。通過 ${}
語法可以使用環境變量,下例展示包含一個名爲當前機器名的配置文件。
<nlog> ... <include file="${machinename}.config" /> ... </nlog>
Variables
variable
元素定義了配置文件中需要用到的變量,一般用來表示複雜或者重複的表達式(例如文件名)。變量需要先定義後使用,否則配置文件將初始化失敗。定義變量的語法如下:
<variable name="var" value="xxx" />
定義變量之後,可以通過 ${var}
語法來使用:
<nlog> <variable name="logDirectory" value="logs/${shortdate}" /> <targets> <target name="file1" xsi:type="File" fileName="${logDirectory}/file1.txt" /> <target name="file2" xsi:type="File" fileName="${logDirectory}/file2.txt" /> </targets> </nlog>
NLog 支持的日誌級別
Trace
- very detailed logs,包含大量的信息,例如 protocol payloads。該級別一般僅在開發環境中啓用。Debug
- debugging information, 比Trance
級別稍微粗略,一般在生產環境中不啓用。Info
- information messages,一般在生產環境中啓用。Warn
- warning messages,一般用於可恢復或臨時性錯誤的非關鍵問題。Error
- error messages,一般是異常信息。Fatal
- 非常嚴重的錯誤!
參考:https://www.cnblogs.com/Can-daydayup/p/11182958.html
https://zhuanlan.zhihu.com/p/35469359
@天才臥龍的波爾卡