应用场景:
控制软件工程拆分为多个子项目,在开发阶段希望每个子项目的日志是单独的。同时又希望日志统一集中定义在Tools(Tools为工具类项目,生成Tools.dll)下,而不是分散在各个子项目中。这就需要解决以下几个问题:
如何在DLL方案中配置Log4net;如何分类Logger;如何在外部使用Logger。
1.在DLL中使用App.config配置Log4net
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net name="DefaultLogger">
<root>
<level value="ALL" />
</root>
<logger name="Doraemon.Default">
<appender-ref ref="DefaultLogger"/>
</logger>
<logger name="Doraemon.Hardware">
<appender-ref ref="HardwareLogger"/>
</logger>
<!-- 统一的无类别日志 -->
<appender name="DefaultLogger" type="log4net.Appender.RollingFileAppender">
<file value="log/default.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="20" />
<maximumFileSize value="256KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<!--硬件日志-->
<appender name="HardwareLogger" type="log4net.Appender.RollingFileAppender">
<file value="log/hardware.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="20" />
<maximumFileSize value="256KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
public static class Logger
{
public static ILog DefaultLogger { get; }
public static ILog HardwareLogger { get; }
static Logger()
{
DefaultLogger = LogManager.GetLogger(@"Doraemon.Default");
HardwareLogger = LogManager.GetLogger("Doraemon.Hardware");
}
}
4.单元测试
[TestMethod]
public void LoggerTest()
{
var loggerCollect = new List<ILog>()
{
DefaultLogger,
HardwareLogger,
};
var select = loggerCollect.FindAll(
(p) =>
p.IsDebugEnabled == p.IsErrorEnabled == p.IsFatalEnabled == p.IsInfoEnabled == p.IsWarnEnabled
);
Assert.AreEqual(loggerCollect.Count, select.Count, "日志对象初始化存在问题");
}