Testing Log4Net Output
We have a custom logging framework setup which is using log4net under the covers. When doing that the ILogger should be used, not the ILog. The ILogger sets up the correct Class information.
Below is some code for testing the output from log4net, this code is just using log4net to write the message, which is not valuable as a test, but when the logging call is replaced with a custom framework you can make sure you’re getting what you expect in your log events.
private MemoryAppender appender;
private LoggingEvent event;
[SetUp]
public void Context()
{
appender.Clear();
// Using log4net here, but should be replace with a custom logging class
// which calls ILogger.Log under it.
LogManager.GetLogger(GetType()).Warn("my test desc.", new Exception("my test exception."));
event = appender.GetEvents()[0];
}
[FixtureSetUp]
public void SetupLog4NetMemoryAppender()
{
appender = new MemoryAppender();
appender.Name = "Unit Testing Appender";
appender.Layout = new log4net.Layout.PatternLayout("%date{dd-MM-yyyy HH:mm:ss,fff} %5level [%2thread] %message (%logger{1}:%line)%n");
appender.Threshold = Level.All;
appender.ActivateOptions();
Logger root = ((Hierarchy) LogManager.GetRepository()).Root;
root.AddAppender(appender);
root.Repository.Configured = true;
}
[FixtureTearDown]
public void RemoveLog4NetMemoryAppender()
{
Logger root = ((Hierarchy)LogManager.GetRepository()).Root;
root.RemoveAppender(appender);
root.Repository.Configured = true;
}
[Test]
public void Should_have_When_logging_type_in_log()
{
var data = _event.GetLoggingEventData();
var info = data.LocationInfo;
info.ClassName.ShouldEqual("Core.Tests.Instrumentation.When_logging_with_CustomLogger");
info.MethodName.ShouldEqual("Context");
}
BTW, the code highlighting was done using the Copy As HTML plug in from here.
Webmentions
These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: