我在log4net如何管理附加程序以及这些附加程序的消息方面遇到问题。
当我将1条消息记录到1个记录器(对应于1个附加程序)时,该消息仍然以所有日志文件结尾(因此,该消息似乎将传递给所有附加程序)
我在做什么错?!
我设法在单元测试中重现我的问题:
[Test]
public void Test()
{
var hierarchy = (Hierarchy)LogManager.GetRepository();
var patternLayout = new PatternLayout
{
ConversionPattern = "%date %level %logger - %message%newline" //CreateLayoutPattern(appenderConfiguration.Layout),
};
patternLayout.ActivateOptions();
hierarchy.Configured = true;
for (var i = 1; i < 10; i++)
{
var logFile = Path.Combine(_testLogFolder, $"SomeLog_Test{i}.csv");
var roller = new RollingFileAppender
{
Name = $"Test{i}",
AppendToFile = true,
File = logFile,
CountDirection = 1,
Layout = patternLayout,
ImmediateFlush = true,
// MaxSizeRollBackups is set to max int, software will have an independent mechanism in place (reaper) to clean up old files
MaxSizeRollBackups = int.MaxValue,
MaximumFileSize = "1MB",
RollingStyle = RollingFileAppender.RollingMode.Size,
StaticLogFileName = false,
PreserveLogFileNameExtension = true,
Threshold = Level.All
};
roller.ActivateOptions();
hierarchy.Root.AddAppender(roller);
}
// A
LogManager.GetLogger("Test1").Info("Whatever");
// Now the ALL of the log files contain the message "Whatever", why?!?! I only logged to 'Test1'
}
显然,这是默认行为(当我考虑更长的时间时才有意义:))。
我需要的是可以实现的。不必将所有附加程序添加到hierarchy.Root.AddAppender
,我必须为每个附加程序名称创建记录器,然后将滚子添加到该记录器。例如:
var logger = hierarchy.GetLogger("Test1", hierarchy.LoggerFactory);
logger.AddAppender(roller);
logger.Level = Level.All;
logger.Additivity = false;
并删除:
hierarchy.Root.AddAppender(roller);