本文轉載:http://www.blogjava.net/qiyadeng/archive/2013/02/27/395799.html
在.net中也有非常多的日志工具,今天介紹下NLog。NLog特別好的地方就是和Vs(Visual Studio)開發環境的集成。
只需下載(下載地址)安裝包,安裝之后NLog就會在VS的新建項中增加很多選項,並且在編輯NLog配置文件時也會提供智能提示和校驗。
NLog工作主要依賴的是兩個文件一個是NLog.dll,另外一個是NLog.config,解下來演示下如何引入和進行配置
1.在你的項目中加入NLog。右擊項目,選擇添加新項目,選擇Empty NLog Configuration,並選擇添加(如圖)。
(說明:有可能不像官網上說的在NLog的目錄下面,在ASP.net Web項目中,會在VB的目錄中。)
在非Asp.net項目中,記得把NLog.config文件復制到輸出目錄(右擊NLog.config文件屬性)。
2.編輯配置文件NLog.config.
關於配置文件如何編輯有大量的篇幅(https://github.com/nlog/nlog/wiki/Configuration-file),我們這里介紹兩種常用的場景。
A)在Vs的輸出窗口輸出日志,關於這些變量的說明${},請參看文檔Configuration Reference。(https://github.com/nlog/nlog/wiki)
<target name="debugger" xsi:type="Debugger" layout="${logger}::${message}" />
B)以文件形式輸出。
layout ="${longdate} ${logger} ${message}"
fileName ="${basedir}/logs/log${shortdate}.txt"
keepFileOpen ="false" />
完整的配置文件例子:
< nlog xmlns ="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" throwExceptions ="true" internalLogFile ="d:\internal_log_file.txt" internalLogLevel ="Trace" internalLogToConsole ="true" >
< targets >
< target name ="debugger" xsi:type ="Debugger" layout ="${logger}::${message}" />
< target name ="file" xsi:type ="File" maxArchiveFiles ="30"
layout ="${longdate} ${logger} ${message}"
fileName ="${basedir}/logs/log${shortdate}.txt"
keepFileOpen ="false" />
</ targets >
< rules >
< logger name ="*" minlevel ="Trace" writeTo ="debugger" />
< logger name ="*" minlevel ="Trace" writeTo ="file" />
</ rules >
</ nlog >
3.在程序中使用NLog
在程序中使用就特別簡單了,和大多數日志工具類似。
namespace MyNamespace
{
public class MyClass
{
private static Logger logger = LogManager.GetCurrentClassLogger();
}
}