为什么世界上的以下测试失败了? (它在xunit中)我尝试过不同的appender并且它从不写任何东西虽然日志似乎已经准备好了。我最终创建了自己的appender来测试它。
public class TestAppender : AppenderSkeleton {
public event Action<LoggingEvent> AppendCalled = delegate { };
protected override void Append(LoggingEvent loggingEvent) {
AppendCalled(loggingEvent);
}
}
public class Class1 {
private TestAppender _appender = new TestAppender();
public Class1() {
log4net.Util.LogLog.InternalDebugging = true;
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
Logger rootLogger = hierarchy.Root;
rootLogger.Level = Level.All;
Logger coreLogger = hierarchy.GetLogger("abc") as Logger;
coreLogger.Level = Level.All;
coreLogger.Parent = rootLogger;
PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = "%logger - %message %newline";
patternLayout.ActivateOptions();
_appender.Layout = patternLayout;
_appender.ActivateOptions();
coreLogger.AddAppender(_appender);
}
[Fact]
public void Test() {
bool called = false;
_appender.AppendCalled += e => called = true;
var log = LogManager.GetLogger("abc");
log.Debug("This is a debugging message");
Thread.Sleep(TimeSpan.FromSeconds(2));
log.Info("This is an info message");
Thread.Sleep(TimeSpan.FromSeconds(2));
log.Warn("This is a warning message");
Thread.Sleep(TimeSpan.FromSeconds(2));
log.Error("This is an error message");
Assert.True(called);
}
}
答案 0 :(得分:42)
我总是使用下面的代码从代码中配置log4net。效果很棒!
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
hierarchy.Root.RemoveAllAppenders(); /*Remove any other appenders*/
FileAppender fileAppender = new FileAppender();
fileAppender.AppendToFile = true;
fileAppender.LockingModel = new FileAppender.MinimalLock();
fileAppender.File = Server.MapPath("/") + "log.txt";
PatternLayout pl = new PatternLayout();
pl.ConversionPattern = "%d [%2%t] %-5p [%-10c] %m%n%n";
pl.ActivateOptions();
fileAppender.Layout = pl;
fileAppender.ActivateOptions();
log4net.Config.BasicConfigurator.Configure(fileAppender);
//Test logger
ILog log =LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log.Debug("Testing!");
答案 1 :(得分:2)
只是猜测那里......
您是否在程序集中定义了XmlConfiguration?
你在测试项目中忘记了吗?
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
这通常会让我偶尔烧伤。
答案 2 :(得分:0)
仍然不能说为什么上面的代码不能正常工作但我得到log4net来正确配置并使用我的appender替换所有的配置代码:
log4net.Config.BasicConfigurator.Configure(_appender);
来自here。