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
-
-
<testfixture ()> _
-
Public Class Log4NetInNUnit
-
-
Private appender As Appender.ConsoleAppender
-
Private Shared log As ILog = LogManager.GetLogger(GetType(ExcelBugs))
-
-
<testfixturesetup ()> _
-
Public Sub InitLog()
-
appender = New Appender.ConsoleAppender()
-
appender.Layout = New Layout.SimpleLayout()
-
appender.Threshold = log4net.Core.Level.All
-
Config.BasicConfigurator.Configure(appender)
-
End Sub
-
-
<testfixtureteardown ()> _
-
Public Sub CleanupLog()
-
appender.Threshold = log4net.Core.Level.Off
-
End Sub
-
-
<test ()> _
-
Public Sub TestLogs()
-
log.Info("test")
-
End Sub
-
End Class
Thanks for this post. It was useful to me :)
Thanks a lot, very useful to me as well!!
This is exactly what I was looking for. Thanks for sharing.
[...] This blog has basic instructions of how to integrate log4net (in VB.Net though). [...]
I tried to call “XmlConfigurator.Configure(new FileInfo(log4net config file path))” which turn out not to work.
This approach works very well~ Thanks