NLog工作主要依賴的是兩個檔案一個是NLog.dll,另外一個是NLog.config,解下來示範下如何引入和進行配置
1.在你的項目中加入NLog。右擊項目,選擇添加新項目,選擇Empty NLog Configuration,并選擇添加(如圖)。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyROBlLtVGdp1ydl5WLkRWYtMndvw1ZuVGZhlXax9CX0VmbfFmdhp2ZvxmYvwFdl5mLhZXYqd2bsJmLzV2Zh1Wavw1LcpDc0RHaiojIsJye.png)
(說明:有可能不像官網上說的在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)
B)以檔案形式輸出。
<target name="file" xsi:type="File" maxArchiveFiles="30"
layout="${longdate} ${logger} ${message}"
fileName="${basedir}/logs/log${shortdate}.txt"
keepFileOpen="false" />
完整的配置檔案例子:
<?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" 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"
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="debugger" />
<logger name="*" minlevel="Trace" writeTo="file" />
</rules>
</nlog>
3.在程式中使用NLog
在程式中使用就特别簡單了,和大多數日志工具類似。
using NLog;
namespace MyNamespace
{
public class MyClass
{
private static Logger logger = LogManager.GetCurrentClassLogger();
}
}