ASP.NET Boilerplate Castle容器无缝添加日志功能

以添加log4net日志框架为例进行讲解

1.通常log4net的配置参数放在单独的配置文件中,但也可以写在web.config中,这里在我们的web项目中添加log4net.config应用配置文件

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender" >
<file value="Logs/Logs.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10000KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level %date [%-5.5thread] %-40.40logger - %message%newline" />
</layout>
</appender>
<root>
<appender-ref ref="RollingFileAppender" />
<level value="DEBUG" />
</root>
<logger name="NHibernate">
<level value="WARN" />
</logger>
</log4net>

2.在程序启动的时候将LoggingFacility添加到容器中

protected override void Application_Start(object sender, EventArgs e)
{
IocManager.Instance.IocContainer.AddFacility<LoggingFacility>(f => f.UseLog4Net().WithConfig("log4net.config"));
base.Application_Start(sender, e);
}

4.Logger是以属性的方式注入的,当需要使用Logger时,通常的用法是

//1.声明一个Logger属性
public ILogger Logger { protected get; set; } //2.在构造函数中给他赋值NullLogger,保证容器在没有解析到Logger时不会报异常
Logger=NullLogger.Instance;

5.注意事项

a) 这些代码依赖的dll有

Castle.Facilities.Logging.dll

Castle.Core.dll

log4net.dll

b) NullLogger.Instance返回一个ILogger实例,Debug、Info等方法内没有代码,什么都没做,详看Castle.Core.Logging源码:

public class NullLogger : IExtendedLogger, ILogger
{
...... public static readonly NullLogger Instance = new NullLogger(); public void Debug(string message, Exception exception)
{
} public void DebugFormat(string format, params object[] args)
{
} ......
}
上一篇:增强Eclipse ,MyEclipse 的代码自动提示功能


下一篇:安装crab