最近有不少朋友推薦我用NLog。我以前都是自己寫txt的文本輸出log,以前別人用log4net的時候看那個配置文件,看得我一陣煩,我比較喜歡約定勝於配置的組件。這次玩了一波NLog,,相當不錯。一下就寫個使用方法。
1.使用命令行下載NLog
Install-Package NLog -Pre
https://www.nuget.org/packages/NLog/
源碼:https://github.com/NLog/NLog
文檔:https://github.com/NLog/NLog/wiki
2.在web.config或者app.config的地方加入配置(不是很多)
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog configSource="NLog.config"></nlog>
這里有個NLog.config,就是具體的配置
3.NLog.config配置
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="file" xsi:type="File" fileName="${basedir}/log_${shortdate}/${longdate}.log" encoding="utf-8" layout="${longdate} [${level}]: ${message}"/>
<target name="coloredConsole" xsi:type="ColoredConsole" encoding="utf-8" layout="${longdate} [${level}]:${message}"/>
<!--<target name="debugger" xsi:type="Debugger" encoding="utf-8" layout="${longdate} [${level}]:${message}"/>-->
<target name="network" xsi:type="Network" address="tcp4://127.0.0.1:10100" encoding="utf-8" keepConnection="true" onOverflow="Split" newLine="false" maxMessageSize="4096">
<layout xsi:type="SimpleLayout">
<text>${longdate} [${level:uppercase=true}] (${logger}): ${message}</text>
</layout>
</target>
</targets>
<rules>
<logger name="*" writeTo="coloredConsole"/>
<logger name="*" writeTo="file"/>
<logger name="*" minlevel="Trace" writeTo="network" />
<!--<logger name="*" writeTo="debugger"/>-->
</rules>
</nlog>
<!--文檔:https://github.com/NLog/NLog/wiki -->
配置中我設置了File,ColoredConsole,debugger,Network,一般本地調試前三者足夠使用,當集群部署系統需要集中log顯示(或者也可以用來做監控,嘿嘿)使用Network傳遞信息。
不過我在使用4.4.5的版本,使用的時候遇到一個問題,當我type是Network的時候,type為debugger要注釋,不然Nlog會失效
4.Demo測試如下
聲明
private static Logger logger = LogManager.GetCurrentClassLogger();
使用
logger.Debug("1111");

DEMO下載地址
