NLog的介紹使用


NLog是什么

NLog是一個基於.NET平台編寫的類庫,我們可以使用NLog在應用程序中添加極為完善的跟蹤調試代碼。
NLog是一個簡單靈活的.NET日志記錄類庫。通過使用NLog,我們可以在任何一種.NET語言中輸出帶有上下文的(contextual information)調試診斷信息,根據喜好配置其表現樣式之后發送到一個或多個輸出目標(target)中。
NLog的API非常類似於log4net,且配置方式非常簡單。NLog使用路由表(routing table)進行配置,這樣就讓NLog的配置文件非常容易閱讀,並便於今后維護。
NLog遵從BSD license,即允許商業應用且完全開放源代碼。任何人都可以免費使用並對其進行測試,然后通過郵件列表反饋問題以及建議。
NLog支持.NET、C/C++以及COM interop API,因此我們的程序、組件、包括用C++/COM 編寫的遺留模塊都可以通過同一個路由引擎將信息發送至NLog中。
簡單來說Nlog就是用來記錄項目日志的組件

NLog日志輸出目標

文件 比如TXT、Excel
文本控制台
Email
數據庫
網絡中的其它計算機(通過TCP或UDP)
基於MSMQ的消息隊列
Windows系統日志

NLog使用

  直接用NuGet安裝就行了

 簡單的Demo

<?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">
  <variable name="myvar" value="myvalue"/>
  <targets>
    <target xsi:type="File" name="SimpleDemoFile" fileName="../../../Logs/SimpleDemo.txt" layout="${message}" encoding="UTF-8"/>
  </targets>
  <rules>
    <logger name="SimpleDemo" level="Error" writeTo="SimpleDemoFile"/>
  </rules>
</nlog>
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _2017011301SimpleDemo
{
    class Program
    {
      public static Logger logger = LogManager.GetLogger("SimpleDemo");
        static void Main(string[] args)
        {
            Console.WriteLine("執行開始");
            logger.Error("Hello World");
            Console.WriteLine("執行結束");
            Console.ReadKey();
        }
    }
}

輸出到  ../../../Logs/SimpleDemo.txt 內容為 Hello World

 

NLog配置

<?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">
<variable name="myvar" value="myvalue"/>
<targets> </targets>
<rules> </rules>
</nlog>

xmlns=“http://www.nlog-project.org/schemas/NLog.xsd” 這表示默認命名空間
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 這個命名空間里面的元素或者屬性就必須要以xsi:這種方式來寫
比如schemaLocation就是他的一個屬性,所以寫成xsi:schemaLocation
而默認命名空間不帶類似xsi這種,其實xml標簽名稱有個專業叫法叫做QName,而如果沒有前面的xsi:這種一般叫做NCName
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
表示把定義這個命名空間的schema文件給引用進來,好讓開發類型工具能夠解析和驗證你的xml文件是否符合語法規范
等同於

簡單來說 上面是用來驗證你XML格式是否正確的。

InternalLogFile="c:\log\nlog.txt" //NLog內部日志文件位置
internalLogLevel="Debug" //日志級別 
autoReload:一旦啟動程序,這時候NLog.config文件被讀取后,知道程序再啟動都不會再讀取配置文件了。假如我們不想停掉程序,比如說服務器哪能說停就停哈。這就用上這個配置了,這個配置功能是,一旦你對配置文件修改,程序將會重新讀取配置文件,也就是自動再配置。

throwExceptions//NLog日志系統拋出異常
internalLogFile="c:\log\nlog.txt" //NLog內部日志文件位置
internalLogLevel="Debug" //日志級別 

<variable /> - 定義配置文件中用到的變量
<targets /> - 定義日志的目標/輸出
<rules /> - 定義日志的路由規則

 

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

NLog記錄等級

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

NLog等級使用

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

 

Logger使用

從配置文件讀取信息並初始化 兩種常用的方式

根據配置的路由名獲生成特定的logger Logger logger = LogManager.GetLogger("LoggerDemo");

初始化為當前命名空間下當前類的logger  Logger logger = LogManager.GetCurrentClassLogger();

區別是logger的name不一樣 前者是LoggerDemo,后者是當前命名空間+點+當前類名 如類比較多,並且往同一個日志文件記錄,建議用GetCurrentClassLogger

 

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

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

Logger發郵件參數

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

<?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="true"
      internalLogLevel="Off"
      internalLogFile="c:\temp\nlog-internal.log">

  <!-- optional, add some variables
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
  <variable name="basePath" value="C:\Users\Zachary\Desktop\練習\20170113NLog\Logs\"/>

  <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"/>
  </targets>

  <rules>
    <logger name="*" level="Error"  writeTo="SendMail"></logger>
  </rules>
</nlog>

 

 

Logger寫入數據庫參數

<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>

 需在數據庫里提前建好表

<?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="true"
      internalLogLevel="Off"
      internalLogFile="../../../Logs/nlog-internal.log">

  <targets>
    <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=你的數據庫密碼;">
    <parameter name="@id" layout="${guid}" />
    <parameter name="@content" layout="${message}" />
    <parameter name="@createTime" layout="${date:format=yyyy\-MM\-dd HH\:mm\:ss.fff} " />
    </target>
  </targets>
  <rules>
    <logger name="Database" level="Error" writeTo="DatabaseFile"/>
  </rules>
</nlog>

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

在configuration配置

<configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>
然后把NLog.config里面放在后面就行了。
<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>

 

 附demo+PPT介紹:http://download.csdn.net/detail/fcydxbd/9740809

 


免責聲明!

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



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