1. 程式人生 > >日誌學習系列(三)——NLog基礎知識

日誌學習系列(三)——NLog基礎知識

  前邊我們解釋了log4net的學習,我們再介紹一下NLog

一、什麼是NLog

  NLog是一個基於.NET平臺編寫的類庫,我們可以使用NLog在應用程式中新增極為完善的跟蹤除錯程式碼。NLog是一個簡單靈活的.NET日誌記錄類庫。

  通過使用NLog,我們可以在任何一種.NET語言中輸出帶有上下文的(contextual information)除錯診斷資訊,根據喜好配置其表現樣式之後傳送到一個或多個輸出目標(target)中。

  NLog遵從BSD license,即允許商業應用且完全開放原始碼。任何人都可以免費使用並對其進行測試,然後通過郵件列表反饋問題以及建議。
  NLog支援.NET、C/C++以及COM interop API,因此我們的程式、元件、包括用C++/COM 編寫的遺留模組都可以通過同一個路由引擎將資訊傳送至NLog中。

二、NLog和Log4net的區別

  NLog的API非常類似於log4net,且配置方式非常簡單。NLog使用路由表(routing table)進行配置,但log4net卻使用層次性的appender配置,這樣就讓NLog的配置檔案非常容易閱讀,並便於今後維護。

三、NLog配置介紹

  

  1、下面的配置是nlog的基礎配置結構

<?xml version="1.0" encoding="utf-8" ?>
<!-- 預設名稱空間 -->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd
"> <!-- 這個名稱空間裡面的元素或者屬性就必須要以xsi:這種方式來寫,比如schemaLocation就是他的一個屬性,所以寫成xsi:schemaLocation。 而預設名稱空間不帶類似xsi這種;其實xml標籤名稱有個專業叫法叫做QName,而如果沒有前面的xsi:這種一般叫做NCName --> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <!--表示把定義這個名稱空間的schema檔案給引用進來,好讓開發型別工具能夠解析和驗證你的xml檔案是否符合語法規範 簡單來說 上面是用來驗證你XML格式是否正確的。
--> xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" <!--一旦啟動程式,這時候NLog.config檔案被讀取後,知道程式再啟動都不會再讀取配置檔案了。假如我們不想停掉程式,比如說伺服器哪能說停就停哈。這就用上這個配置了,這個配置功能是,一旦你對配置檔案修改,程式將會重新讀取配置檔案,也就是自動再配置。--> autoReload="true" <!--NLog日誌系統丟擲異常--> throwExceptions="false" <!--日誌級別 --> internalLogLevel="Debug" <!--NLog內部日誌檔案位置 --> internalLogFile="c:\temp\nlog-internal.log"> <!--variable定義配置檔案中用到的變數--> <variable name="myvar" value="myvalue"/> <!--定義日誌的目標/輸出--> <targets> </targets> <!--定義日誌的路由規則--> <rules> </rules> </nlog>

  2、NLog的重要配置說明

    (1)Layout佈局

      幾種常見的

      ${var:basePath} basePath是前面自定義的變數
      ${longdate} 日期格式 2017-01-17 16:58:03.8667
      ${shortdate}日期格式 2017-01-17 
      ${date:yyyyMMddHHmmssFFF} 日期 20170117165803866
      ${message} 輸出內容
      ${guid} guid
      ${level}日誌記錄的等級
      ${logger} 配置的logger

    (2)NLog記錄等級

      Trace - 最常見的記錄資訊,一般用於普通輸出
      Debug - 同樣是記錄資訊,不過出現的頻率要比Trace少一些,一般用來除錯程式
      Info - 資訊型別的訊息
      Warn - 警告資訊,一般用於比較重要的場合
      Error - 錯誤資訊
      Fatal - 致命異常資訊。一般來講,發生致命異常之後程式將無法繼續執行。
      自上而下,等級遞增。

    (3)NLog等級使用

      指定特定等級 如:level="Warn" 
      指定多個等級 如:levels=“Warn,Debug“ 以逗號隔開
      指定等級範圍 如:minlevel="Warn" maxlevel="Error"

 

    (4)Logger使用

      從配置檔案讀取資訊並初始化 兩種常用的方式

      方法一:根據配置的路由名獲生成特定的logger:

         Logger logger = LogManager.GetLogger("LoggerDemo");

      方法二:初始化為當前名稱空間下當前類的logger :

        Logger logger = LogManager.GetCurrentClassLogger();

    區別是logger的name不一樣 前者是LoggerDemo,後者是當前名稱空間+點+當前類名 如類比較多,並且往同一個日誌檔案記錄,建議用GetCurrentClassLogger

 

    (5)Logger有以下三種常用的寫入方式

      logger.Error("這是DatabaseDemo的錯誤資訊");
      logger.Error(“ContentDemo {0}:{1}”,“時間”,DateTime.Now.ToString());需要拼接字串的話推薦這種,NLog做了延遲處理,用的時候才拼接。
      logger.Log(LogLevel.Error, "這是ContentDemo");

    (6)Logger發郵件引數

      smtpServer=“*****” 郵件伺服器 例如126郵箱是smtp.126.com
      smtpPort=“25“埠
      smtpAuthentication=“Basic“ 身份驗證方式 基本
      smtpUserName=“*****“ 郵件伺服器使用者名稱
      smtpPassword=“******”郵件伺服器密碼
      enableSsl=“false”是否使用安全連線 需要伺服器支援
      addNewLines=“true” 開頭與結尾是否換行
      from=“****” 發件郵箱
      to=“[email protected],[email protected]”收件郵箱 多個以逗號分隔
      subject=“subject:${machinename}報錯“ 郵件主題
      header=“---------------------開頭-------------------------“ 郵件開頭
      body=“${newline}${message}${newline}“ 郵件內容
      footer=“---------------------結尾-------------------------“ 郵件結尾

  3、NLog例項

  

<?xml version="1.0" encoding="utf-8" ?>
<!--nlog教程詳情:http://www.cnblogs.com/dflying/archive/2006/12/04/581750.html-->

<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}" />
    -->
    <target name="console" xsi:type="Console"/>
    <target name="file" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log"
      layout="${longdate} ${callsite} ${level}:${message} ${event-context:item=exception} ${stacktrace} ${event-context:item=stacktrace}"/>
    </targets>

    <target xsi:type="Mail"
      name="SendMail"
      smtpServer="你的郵件伺服器"
      smtpPort="你的郵件伺服器埠"
      smtpAuthentication="Basic"
      smtpUserName="你的郵件伺服器名"
      smtpPassword="你的郵件伺服器密碼"
      enableSsl="false"
      addNewLines="false"
      from="你的發件郵箱"
      to="你的收件郵箱"
      subject="subject:${machinename}報錯"
      header="---------------------開頭-------------------------"
      body="${newline}${message}${newline}"
      footer="---------------------結尾-------------------------"
      encoding="UTF-8"/>

    <target xsi:type="Database"
      name="DatabaseFile"
      dbProvider=“System.Data.SqlClient”資料庫型別
      commandText=“Insert into ErrorLog(ID, Content, CreateTime) Values(@id, @content, @createTime);”插入操作
      connectionString=“data source=.;initial catalog=NLog;user id=sa;password=******;”> 資料庫連線字串 跟我們webcofig中的一樣
      <parameter name=“@id” layout=“${guid}” /> 引數
      <parameter name="@content" layout="${message}" />
      <parameter name="@createTime" layout="${date:format=yyyy\-MM\-dd HH\:mm\:ss.fff} " />
    </target>

  <rules>   
    <!--
    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" />
    -->
    <logger name="*" minlevel="Info" writeTo="console"/>
    <logger name="*" minlevel="Trace" writeTo="file"/>
   <logger name="*" level="Error"  writeTo="SendMail"></logger>

   <logger name="Database" level="Error" writeTo="DatabaseFile"/>

</rules> </nlog>

四、NLog配置的注意事項

  NLog.config可以單獨放,也可以放在WebConfig裡。

  1、放在webconfig中示例

  

<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>
  <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="true"
      internalLogLevel="Off"
      internalLogFile="c:\temp\nlog-internal.log">
    <variable name="myvar" value="myvalue"/>
    <targets async="false">
      <target xsi:type="File" name="WebDemoFile" fileName="C:\Users\Zachary\Desktop\練習\20170113NLog\Logs\${date:yyyyMMddHHmm}WebDemo.txt" layout="${longdate} ${message}" encoding="UTF-8"/>
    </targets>
    <rules>
      <logger name="WebDemo" level="Error" writeTo="WebDemoFile"/>
    </rules>
  </nlog>
</configuration>

  2、單獨放置

  新建一個NLog.config檔案

  

<?xml version="1.0" encoding="utf-8" ?>
<!--nlog教程詳情:http://www.cnblogs.com/dflying/archive/2006/12/04/581750.html-->

<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}" />
    -->
    <target name="console" xsi:type="Console"/>
    <target name="file" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log"
      layout="${longdate} ${callsite} ${level}:${message} ${event-context:item=exception} ${stacktrace} ${event-context:item=stacktrace}"/>
  </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" />
    -->
    <logger name="*" minlevel="Info" writeTo="console"/>
    <logger name="*" minlevel="Trace" writeTo="file"/>
  </rules>
</nlog>