Thursday, July 17, 2014

Capturing log messages in the MSTest Unit Test Output with Common.Logging

Lately I've been enjoying the abstraction of a logging facade in my .NET apps, specifically the Common.Logging project. This provides me with a simple, standard interface for logging in my code which I can configure to output to a variety of destinations. Typically I send the logging output through NLog to a combination of outputs (file, email, event log, etc), but the beauty of using a logging facade is that you can change how the log messages are handled without changing your production code.

Today I though it would be nice to see what my code was logging during my unit tests, and I didn't want to dig through a log file to find the log from one specific test. Since the unit test runner is a different executing assembly than my web project, it can have it's own configuration for logging separate from the application. Knowing this, I should be able to set up this new logging behavior for my tests without changing anything in my main project's configuration.

So what makes it possible to log messages from Common.Logging to the standard unit test output?
  • Anything written to Console.Out during a unit test will get captured in the unit test Output.
  • Common.Logging ships with a built-in Console.Out logger adapter that we can use without requiring a larger logging framework.
Knowing these two facts, we can implement this easily in a Unit Test Project:
  1. The code being tested should be doing its logging through the Common.Logging log methods.
  2. Using NuGet, install the Common.Logging package into your unit test project
  3. In the unit test project's App.Config file, add the necessary XML to configure the console logger (See XML snippet below)
  4. Run your unit test(s)
  5. See the log messages captured during each test in your test output:
And of course, let's not forget the code and configuration details:

1 comment:

  1. Great, I was looking for this functionality. Quick question can we save the DEBUG info in a file too.
    Thanks
    Jay

    ReplyDelete

Note: Only a member of this blog may post a comment.