在代码中通过 XML 配置 log4net:
string xml =
@"<log4net>
<appender name='file1' type='log4net.Appender.RollingFileAppender'>
<!-- Log file locaation -->
<param name='File' value='log4net.log'/>
<param name='AppendToFile' value='true'/>
<!-- Maximum size of a log file -->
<maximumFileSize value='2KB'/>
<!--Maximum number of log file -->
<maxSizeRollBackups value='8'/>
<!--Set rolling style of log file -->
<param name='RollingStyle' value='Composite'/>
<param name='StaticLogFileName' value='false'/>
<param name='DatePattern' value='.yyyy-MM-dd.lo\g'/>
<layout type='log4net.Layout.PatternLayout'>
<param name='ConversionPattern' value='%d [%t] %-5p %m%n'/>
</layout>
</appender>
<!-- Appender layout fix to view in console-->
<appender name='console' type='log4net.Appender.ConsoleAppender'>
<layout type='log4net.Layout.PatternLayout'>
<param name='Header' value='[Header]\r\n'/>
<param name='Footer' value='[Footer]\r\n'/>
<param name='ConversionPattern' value='%d [%t] %-5p %m%n'/>
</layout>
</appender>
<appender name='debug' type='log4net.Appender.DebugAppender'>
<layout type='log4net.Layout.PatternLayout'>
<param name='ConversionPattern' value='%d [%t] %logger %-5p %m%n'/>
</layout>
</appender>
<root>
<level value='INFO'/>
<!--
Log level priority in descending order:
FATAL = 1 show log -> FATAL
ERROR = 2 show log -> FATAL ERROR
WARN = 3 show log -> FATAL ERROR WARN
INFO = 4 show log -> FATAL ERROR WARN INFO
DEBUG = 5 show log -> FATAL ERROR WARN INFO DEBUG
-->
<!-- To write log in file -->
<appender-ref ref='debug'/>
<appender-ref ref='file1'/>
</root>
</log4net>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
log4net.Config.XmlConfigurator.Configure(doc.DocumentElement);
在代码中通过 XML 配置 NLog(适用于 NLog 2.0 及更高版本):
string xml = @"<nlog>
<targets>
<target name='console' type='Console' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='Error' writeTo='console' />
</rules>
</nlog>";
StringReader sr = new StringReader(xml);
XmlReader xr = XmlReader.Create(sr);
XmlLoggingConfiguration config = new XmlLoggingConfiguration(xr, null);
LogManager.Configuration = config;
//NLog is now configured just as if the XML above had been in NLog.config or app.config
在 NLog 2.0 之前,NLog 的 XmlLoggingConfiguration 对象在其构造函数中不采用 XmlReader。您可以改为传递 XmlElement,如下所示:
string xml = @"<nlog>
<targets>
<target name='debugger' type='Console' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='Error' writeTo='console' />
</rules>
</nlog>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlLoggingConfiguration config = new XmlLoggingConfiguration(doc.DocumentElement,null);
LogManager.Configuration = config;
要更新配置,给定一个新的 XML 字符串,只需对您正在使用的特定日志记录框架重复这些步骤。