Blog on software engineering
How to redirect the standard console output, to assert logmessages written by log4net.

How to redirect the standard console output, to assert logmessages written by log4net.

By using a log4net ConsoleAppender, you can write all log messages in your application to the console. These message will show up in the Microsoft Visual Studio output window. I needed a way to redirect the messages written to the console, so I could verify if the correct messages were send to the console. For this task I redirected the standard console output in my unit test:

 

Code

using System;
using System.IO;
using System.Text;
using log4net;
using log4net.Config;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            // Save original console output writer.
            TextWriter originalConsole = Console.Out;

            // Configure log4net based on the App.config
            XmlConfigurator.Configure();

            var builder = new StringBuilder();
            using (var writer = new StringWriter(builder))
            {
                // Redirect all Console messages to the StringWriter.
                Console.SetOut(writer);

                // Log a debug message.
                ILog logger = LogManager.GetLogger("Unittest logger");
                logger.Debug("This is a debug message");
            }

            // Get all messages written to the console.
            string consoleOutput = string.Empty;
            using (var reader = new StringReader(builder.ToString()))
            {
                consoleOutput = reader.ReadToEnd();
            }

            // Assert.
            string expected = "This is a debug message" + Environment.NewLine;
            Assert.AreEqual(expected, consoleOutput);

            // Redirect back to original console output.
            Console.SetOut(originalConsole);
        }
    }
}

App.config

 

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
  </configSections>
  <log4net>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message%newline" />
      </layout>
    </appender>
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="ConsoleAppender" />
    </root>
  </log4net>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

Microsoft Visual Studio

 

image

 

I used NuGet to add a reference to the latest log4net build.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.