1. 程式人生 > 程式設計 >.NET日誌框架Nlog使用介紹

.NET日誌框架Nlog使用介紹

目錄
  • 快速安裝
  • 快速配置
  • 快速使用
  • 詳解配置
    • 新增支援Console輸出
    • 輸出至CSV檔案
  • 配置日誌大小
    • 配置日誌分級
      • 配置生成規則
        • 日誌過濾器
          • 條件語言
          • 條件函式

        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://.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.http://www.cppcns.com
        <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()zhkeyTnpWv;
                }
            }

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

        .NET日誌框架Nlog使用介紹

        詳解配置

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

        .NET日誌框架Nlog使用介紹

        新增支援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輸出

        .NET日誌框架Nlog使用介紹

        輸出至CSV檔案

        1.在rules中新增一個新的路由,以支援csv檔案,並且新增一http://www.cppcns.com個目標,輸出至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"),輸出的效果如下:

        .NET日誌框架Nlog使用介紹

        配置日誌大小

        Nlog允許使用者配置單個檔案大小,放置在內容過長效率過慢,配置了大小之後,Nlog會自動建立一個新的檔案副本,插入新的日誌輸出。

        • maxArchiveFiles: 允許生成的副本檔案最大數量
        • archiveAboveSize: 允許單個檔案得最大容量
        • archiveEvery: 按天生成
        • layout: 當前得內容佈局格式
        • 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>
                &lt;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="lengthwww.cppcns.com('${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')

        到此這篇關於.NET日誌框架Nlog使用介紹的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支援我們。