如何在运行时添加额外的日志追加器? (所有预先存在的appender必须继续工作)
我这样试试:
var layout = new PatternLayout("%utcdate %-5level - %message%newline");
layout.ActivateOptions();
_log4netAppender = new FileAppender
{
Layout = layout,
File = logFilePath,
};
_log4netAppender.ActivateOptions();
BasicConfigurator.Configure(_log4netAppender);
但它不会向文件写任何内容。
答案 0 :(得分:18)
您还应该将appender添加到记录器中。 看看Adding Appenders programmatically
如果您使用的记录器是,例如ILog logger
,请执行:
((log4net.Repository.Hierarchy.Logger)logger.Logger).AddAppender(appender)
答案 1 :(得分:0)
var patternLayout = new log4net.Layout.PatternLayout
{
ConversionPattern = "%date %level %message%newline"
};
patternLayout.ActivateOptions();
var rollingFileAppender = new log4net.Appender.RollingFileAppender
{
File = "MyApp.log",
Layout = patternLayout
};
rollingFileAppender.ActivateOptions();
var hierarchy = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository();
hierarchy.Root.AddAppender(rollingFileAppender);
hierarchy.Root.Level = log4net.Core.Level.All; // Default is Debug
log4net.Config.BasicConfigurator.Configure(hierarchy);