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:



using System;
using System.IO;
using System.Text;
using log4net;
using log4net.Config;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestProject1
public class UnitTest1
public void TestMethod1()
// Save original console output writer.
TextWriter originalConsole = Console.Out;
// Configure log4net based on the App.config
var builder = new StringBuilder();
using (var writer = new StringWriter(builder))
// Redirect all Console messages to the StringWriter.
// 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.



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

Microsoft Visual Studio




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 *