對於.net程序記錄log的主流控件,有:log4net和NLog
log4net比較老牌,但是log4net截止到2017年就不再更新了,而NLog更新比較活躍,我比較喜歡長期有更新的控件~~
功能上沒有什麼差別。
使用方法:
1. Nuget安裝NLog和NLog.config兩個庫
2. 配置config文件
3. 代碼中使用
操作代碼:
NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
log.Trace("記錄一條Trace log");
log.Debug("記錄一條Debug log");
log.Info("記錄一條Info log");
log.Warn("記錄一條Waring log");
log.Error("記錄一條Error log");
log.Fatal("記錄一條Fatal log");
配置文件:
<?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">
<!-- optional, add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/>
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets>
<target name="log_file" xsi:type="File"
fileName="${basedir}/Logs/${shortdate}.txt"
layout="${longdate} | ${level:uppercase=false:padding=-5} ${message} ${onexception:${exception:format=toString} ${newline} ${stacktrace} ${newline} ${DatabaseName}" />
<!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
-->
<!--
Write events to a file with the date in the filename.
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
</targets>
<rules>
<logger name="*" levels="Trace" writeTo="log_file" />
<logger name="*" levels="Debug" writeTo="log_file" />
<logger name="*" levels="Info" writeTo="log_file" />
<logger name="*" levels="Warn" writeTo="log_file" />
<logger name="*" levels="Error" writeTo="log_file" />
<logger name="*" levels="Fatal" writeTo="log_file" />
<!-- add your logging rules here -->
<!--
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
</rules>
</nlog>
使用效果: