How To Get log4net Messages to Show Up In NUnit’s Console.Out

I’ve been using log4net (a port of log4j to .net) for a while now. I’ve always loved how configurable it was: I could have it send me email, log to xml, a database, whatever.

I’ve also been using NUnit to do TDD. Sometimes when a test crashes I would love to have the log output to work with. Often, since I didn’t have the logs, I would use TestDriven.NET‘s test with debugger feature and start debugging. Lately I’ve been trying to get away from that as I think it will lead to better tests.

Anyway, I needed a way to view the log in NUnit’s gui or the TestDriven.NET window. I figured I would share what I came up with in the hopes that someone will find it useful. It’s written in vb.net because that is what the project was using. It’s all in code since I didn’t want my tests dependant on an external config file.

Note: If you have log4net configured this code will alter the logging configuration for the rest of the test run.

Imports NUnit.Framework
Imports log4net

 _
Public Class Log4NetInNUnit

	Private appender As Appender.ConsoleAppender
	Private Shared log As ILog = LogManager.GetLogger(GetType(ExcelBugs))

	 _
	Public Sub InitLog()
		appender = New Appender.ConsoleAppender()
		appender.Layout = New Layout.SimpleLayout()
		appender.Threshold = log4net.Core.Level.All
		Config.BasicConfigurator.Configure(appender)
	End Sub

	 _
	Public Sub CleanupLog()
		appender.Threshold = log4net.Core.Level.Off
	End Sub

	 _
	Public Sub TestLogs()
		log.Info("test")
	End Sub
End Class
Posted in Software Development and tagged . Permalink.

6 Responses to How To Get log4net Messages to Show Up In NUnit’s Console.Out

  1. Thanks for this post. It was useful to me :)

    Ari
  2. Thanks a lot, very useful to me as well!!

    Pejvan
  3. This is exactly what I was looking for. Thanks for sharing.

    Scott
  4. Pingback: First Steps with Selenium and NUnit « devioblog

  5. I tried to call “XmlConfigurator.Configure(new FileInfo(log4net config file path))” which turn out not to work.
    This approach works very well~ Thanks

  6. Actually, the XmlConfigurator approach works correctly, so long as you use the ConsoleAppender instead of the ColoredConsoleAppender

    Matthew

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>