好的,这个问题已经在谷歌上,我已经找到了答案,所以我就把它留在这里。:)
操作 appender 的关键是IAppenderAttachable
接口,因为它实现AddAppender
了removeAppender
方法。
返回的LogManager.GetLogger()
是 的实例ILog
,该实例又包含属性Logger
。返回的对象ILog.Logger
是一个Logger
类实例。Logger
类实现IAppenderAttachable
接口并包含Repository
用于提取记录器存储库的属性。存储库具有GetAppenders
返回AppenderCollection
类实例(实现ICollection
、、、IList
等Ienumerable
)的方法以及记录器的所有活动附加器。
总结一下:
//no need to put it in the static constructor, but in my case it is so
static Logger()
{
logger = LogManager.GetLogger(...);
if (logger.Logger.Repository.GetAppenders().Length == 0) {
(logger.Logger as IAppenderAttachable).AddAppender(CreateConsoleAppender());
}
}
private static ConsoleAppender CreateConsoleAppender()
{
var appender = new ConsoleAppender();
appender.Layout = CreateDefaultLayout();
appender.AddFilter(CreateDefaultFilter());
appender.ActivateOptions(); // if omitted - throws an excpetion
log4net.Config.BasicConfigurator.Configure(appender); //if omitted - no errors, but logging does not work
return appender;
}
private static ILayout CreateDefaultLayout()
{
PatternLayout layout = new PatternLayout();
layout.ConversionPattern = "%d{yyyy-MM-dd hh:mm:ss} - %level %m%n";
layout.ActivateOptions();
return layout;
}
private static IFilter CreateDefaultFilter()
{
LevelRangeFilter filter = new LevelRangeFilter { LevelMin = Level.Info };
filter.ActivateOptions();
return filter;
}
请注意,如果文件丢失或损坏log4net
,则不会抛出任何异常(至少开箱即用),但不会将附加程序附加到记录器。