Puerto Puerto - 1 year ago 124
C# Question

Log4net not working with NUnit tests

So I've done some looking around. Most of the threads I find seem related to people wanting to run log4net in their actual tests. Meaning they want log entries in their test class. I don't want log entries from my actual tests. But I do want the expected log entries from the code I am testing. This is my first time using Log4net. If I run the code on it's own, the log entries work. If I run a test, no log entries though. Im guessing it's not initialized properly or perhaps I don't have log4net setup correctly in my UnitTest (in appconfig or assembly maybe??). This is an MVC 5 application. Here is a basic example.

Nunit Test (basics):

namespace MyUnitTests
public class MyTestClass
public void MyTest
var testVar = @"string";


//assert something

so over in MyProject I have (basics):

public class MyProjectClass : Controller
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(MyProjectClass));

public static void Method(string myString)
//does whatever
log("added value");

So I've obviously simplified this for the discussion. But when I run my actual test, my test passes, the values and the outcome are all as they should be. I just never see the log entry in the log for method I just tested. Im sure I'm missing something simple. Any help would be greatly appreciated. Thanks!

Answer Source

If you look in the app.config for your main project, you should see a log4net config section that specifies the location of the log file.

You first need to add log4net to your <configSections> like this:

<configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=, Culture=neutral, PublicKeyToken=1b44e1d426115821" /> </configSections>

You can then add a <log4net> section to the <configuration> tag. Documentation for this can be found here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download