Nlog 日志框架使用介紹


NLog是一個基於.NET平台編寫的類庫,我們可以使用NLog在應用程序中添加極為完善的跟蹤調試代碼。
NLog是一個簡單靈活的.NET日志記錄類庫。通過使用NLog,我們可以在任何一種.NET語言中輸出帶有上下文的(contextual information)調試診斷信息,根據喜好配置其表現樣式之后發送到一個或多個輸出目標(target)中。

如果嫌棄字多懶得看, 點擊跳轉視頻地址

快速安裝

在軟件包管理器控制台中使用GUI或以下命令:
1.安裝Nlog

Install-Package Nlog

2.安裝Nlog.Config

Install-Package Nlog.Config

快速配置

打開目錄中得Nlog.Config文件, 可以注意到, XML文件中有詳細說明, rules區允許添加用戶自定義得路由規則, targets則用於配置一些輸出目標, 如下:

<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  <!-- optional, add some variables
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
  <variable name="myvar" value="myvalue"/>

  <!--
  See https://github.com/nlog/nlog/wiki/Configuration-file
  for information on customizing logging rules and outputs.
   -->
  <targets>

    <!--
    add your targets here
    See https://github.com/nlog/NLog/wiki/Targets for possible targets.
    See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
    -->

    <!--
    Write events to a file with the date in the filename.
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    -->
  </targets>

  <rules>
    <!-- add your logging rules here -->

    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    <logger name="*" minlevel="Debug" writeTo="f" />
    -->
  </rules>
</nlog>

我們暫時把注釋的說明代碼移除, 還原到最簡潔得XML格式, 如下:

<?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" >
  <targets>
    <!--這個目標:最終輸出文件類型, 位於根目錄中得logs文件夾中, 名稱以每日得時間一次生成log文件 , layout: 這個選項為生成的格式-->
    <target xsi:type="File" name="f" 
            fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
  </targets>

  <rules>
    <!--設定了一個Debug得路由, 最終指向了一個f名稱得目標 -->
    <logger name="*" minlevel="Debug" writeTo="f" />
  </rules>
</nlog>

快速使用

1.創建Nlog實例

private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

2.使用Debug進行輸出
由於在Nlog.Config當中, 我們已經添加了Debug的最終輸出目標, 所以我們嘗試輸出Debug的內容:

 class Program
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        static void Main(string[] args)
        {
            Logger.Debug("我出現了意外!");

            Console.ReadKey();
        }
    }

運行完成之后,可以在當前的輸出目錄中, 發生已經生成了一個logs的文件夾,並且生成了當前計算器日期的log文件 (這個規則在Nolog.Config當中可以進行配置), 如圖所示:

詳解配置

關於rules中, 我們可以添加多種路由規則, 並且指向多個目標, 如下所示:

添加支持Console輸出

1.在rules中添加Info, writeTo指向一個Console的目標

<targets>
    <!--<target xsi:type="File" name="f" 
            fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />-->
    <target xsi:type="Console" name="console"/>
  </targets>

  <rules>
    <!--<logger name="*" minlevel="Debug" writeTo="f" />-->
    <logger name="*" minlevel="Info" writeTo="console"/>
  </rules>

2.使用Info輸出

輸出至CSV文件

1.在rules中添加一個新的路由, 以支持csv文件, 並且添加一個目標, 輸出至csv文件, column可以用於指定每列生成的數據內容格式

    <targets>
        <target name="csv" xsi:type="File" fileName="${basedir}/file.csv">
            <layout xsi:type="CSVLayout">
                <column name="time" layout="${longdate}" />
                <column name="message" layout="${message}" />
                <column name="logger" layout="${logger}"/>
                <column name="level" layout="${level}"/>
            </layout>
        </target>
    </targets>
 
    <rules>
        <logger name="*" minlevel="Debug" writeTo="csv" />
    </rules>

最終調用Debug("xxxx"), 輸出的效果如下:

配置日志大小

Nlog允許用戶配置單個文件大小, 放置在內容過長效率過慢,配置了大小之后, Nlog會自動創建一個新的文件副本,插入新的日志輸出。

  1. maxArchiveFiles: 允許生成的副本文件最大數量
  2. archiveAboveSize: 允許單個文件得最大容量
  3. archiveEvery: 按天生成
  4. layout: 當前得內容布局格式
  5. fileName: 包含完整得生成文件得路徑喝文件名
<targets>
    <target name="file" xsi:type="File"
        layout="${longdate} ${logger} ${message}${exception:format=ToString}"
        fileName="${basedir}/logs/logfile.txt"
        maxArchiveFiles="5"
        archiveAboveSize="10240"
        archiveEvery="Day" />
  </targets>

  <rules>
    <logger name="*" minlevel="Debug" writeTo="file" />
  </rules>

配置日志分級

單個文件目標可用於一次寫入多個文件。以下配置將導致每個日志級別的日志條目被寫入一個單獨的文件,支持以下格式:
Trace.log
Debug.log
Info.log
Warn.log
Error.log
Fatal.log
只需要在Nlog.Config中配置以下內容即可:

<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 
    <targets>
        <target name="file" xsi:type="File"
            layout="${longdate} ${logger} ${message}${exception:format=ToString}" 
            fileName="${basedir}/${level}.log" />
    </targets>
 
    <rules>
        <logger name="*" minlevel="Debug" writeTo="file" />
    </rules>
</nlog>

配置生成規則

只需要將filename中編寫得固定名稱修改程 ${shortdate} 即可

<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 
    <targets>
        <target name="file" xsi:type="File"
            layout="${longdate} ${logger} ${message}${exception:format=ToString}" 
            fileName="${basedir}/${shortdate}.log" />
    </targets>
 
    <rules>
        <logger name="*" minlevel="Debug" writeTo="file" />
    </rules>
</nlog>

日志過濾器

可以在路由當中, 為每個路由配置自定義得日志過濾器fliter, 如下所示, 演示了使用各種表達式來配置過濾器:

<rules>
    <logger name="*" writeTo="file">
        <filters>
            <when condition="length('${message}') > 100" action="Ignore" />
            <when condition="equals('${logger}','MyApps.SomeClass')" action="Ignore" />
            <when condition="(level >= LogLevel.Debug and contains('${message}','PleaseDontLogThis')) or level==LogLevel.Warn" action="Ignore" />
            <when condition="not starts-with('${message}','PleaseLogThis')" action="Ignore" />
        </filters>
    </logger>
</rules>

條件語言

過濾器表達式以特殊的迷你語言編寫。該語言包括:
關系運算符:==,!=,<,<=,>=和>
注意:一些預先定義的XML字符可能需要轉義。例如,如果嘗試使用'<'字符,則XML解析器會將其解釋為開始標記,這會導致配置文件中的錯誤。而是<在這種情況下使用轉義版本的<<(())。
布爾運算符:and,or,not
始終被視為布局的字符串文字- ${somerenderer}
布爾文字- true和false
數值文字-例如12345(整數文字)和12345.678(浮點文字)
日志級別文字- LogLevel.Trace,LogLevel.Debug,...LogLevel.Fatal
預定義的關鍵字來訪問最常用的日志事件屬性- level,message和logger
花括號-一起覆蓋默認優先級和分組表達式
條件函數-執行string和object測試
單引號應與另一個單引號轉義。

條件函數

以下條件功能可用:
contains(s1,s2)確定第二個字符串是否是第一個的子字符串。返回:true當第二個字符串是第一個字符串的子字符串時,false否則返回。
ends-with(s1,s2)確定第二個字符串是否是第一個字符串的后綴。返回:true當第二個字符串是第一個字符串的前綴時,false否則返回。
equals(o1,o2)比較兩個對象是否相等。返回:true當兩個對象相等時,false否則返回。
length(s) 返回字符串的長度。
starts-with(s1,s2)確定第二個字符串是否是第一個字符串的前綴。返回:true當第二個字符串是第一個字符串的前綴時,false否則返回。
regex-matches(input, pattern, options)在NLog 4.5中引入。指示正則表達式是否pattern在指定的input字符串中找到匹配項。options是一個可選的逗號分隔的RegexOptions枚舉值列表。
返回:true當在輸入字符串中找到匹配項時,false否則返回。
范例:regex-matches('${message}', '^foo$', 'ignorecase,singleline')

關於更多內容

訪問: https://github.com/NLog/NLog , 查看更多內容


免責聲明!

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



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