17

如何在运行时添加额外的日志附加器?(所有预先存在的附加程序必须继续工作)
我正在尝试这种方式:

        var layout = new PatternLayout("%utcdate %-5level - %message%newline");
        layout.ActivateOptions();
        _log4netAppender = new FileAppender
            {
                Layout = layout,
                File = logFilePath,
            };
        _log4netAppender.ActivateOptions();
        BasicConfigurator.Configure(_log4netAppender);

但它不会向文件写入任何内容。

4

2 回答 2

21

您还应该将附加程序添加到记录器。看看这里以编程方式添加附加程序

如果您使用的记录器是,例如ILog logger

((log4net.Repository.Hierarchy.Logger)logger.Logger).AddAppender(appender)

于 2013-11-07T10:47:17.507 回答
2
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);
于 2020-10-19T23:45:03.430 回答