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
文本控制台
資料庫
網絡中的其它計算機(通過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=“[email protected],[email protected]”收件郵箱 多個以逗号分隔
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>