无法以编程方式配置log4net Logger

时间:2018-10-21 06:28:38

标签: log4net configure programmatically

我需要以编程方式配置log4net Logger。具体来说,我需要添加一个带有附加器的Logger。但是,当我检索它时,发现它没有正确的级别或附加程序,并希望我错过了一些简单的配置仪式:

        var patternLayout = new PatternLayout { ConversionPattern = "%message%newline" };
        patternLayout.ActivateOptions();

        var hierarchy = (Hierarchy)LogManager.GetRepository();

        var testAppender = new RollingFileAppender
        {
            Name = "test-appender",
            AppendToFile = true,
            File = "c:\\temp\\test.log",
            Layout = patternLayout,
            DatePattern = "yyyyMMdd-HHmm",
            MaxSizeRollBackups = 50,
            MaximumFileSize = "20MB",
            RollingStyle = RollingFileAppender.RollingMode.Size,
            StaticLogFileName = false,
            Encoding = Encoding.UTF8,
            PreserveLogFileNameExtension = true,
            Threshold = Level.Debug
        };

        testAppender.ActivateOptions();

        var testLogger = hierarchy.LoggerFactory.CreateLogger(hierarchy, "test");
        testLogger.Hierarchy = hierarchy;
        testLogger.AddAppender(testAppender);
        testLogger.Repository.Configured = true;
        testLogger.Level = Level.Debug;
        testLogger.Additivity = false;

        hierarchy.Configured = true;

        var testLogger = LogManager.GetLogger("test");

记录器“ testLogger”的级别为空,没有附加程序。我想念什么?

1 个答案:

答案 0 :(得分:0)

代替呼叫

var testLogger = hierarchy.LoggerFactory.CreateLogger(hierarchy, "test");

我打电话

var testLogger = hierarchy.GetLogger("test", hierarchy.LoggerFactory);

那行得通。如果尚不存在,则GetLogger将创建记录器。