Tag: LOGGING

Redirecting the console output in c#

Posted by – September 17, 2009

Often when writing code in an agile way, the best way. We might write something like this.

 Console.WriteLine("I'm super awesome"); 

I don’t think it’s the correct way to do logging in your game or application. But such is life, stuff happens and we’re tasked with resolving it.

We need to get all these logging messages into some readable form inside my game, or app. This needs to be done by the time you wake up yesterday.

So how do we replace potentially hundreds and hundreds of Console.WriteLine’s?

Don’t panic, I have a solution. We can redirect the Console output to anything we want. All we need is an IO Stream and we can do whatever we like with it.

I decided to do this and output it to a label which scrolls in my application. It’s not the most ideal solution for viewing it either, but we went from not knowing W.T.F was going on, to seeing snippets of info fly by. It allowed us to progress with the next problem. This was a minor change and isn’t required to be in the final product so it doesn’t have to be “pretty” per say.

Here’s how I did it. I inherit from the class TextWriter and override the WriteLine method. I just happen to know all my logging calls are coming into WriteLine. Your situation may require more methods to override.

I expose an event which fires every time WriteLine is called and my app picks this up and displays it on screen. Here’s the full class

 public class TextBoxWriter : TextWriter
{
    public event Action<string> OnConsoleWriteLine;

    public override void Write(string message)
    {
        this.OnConsoleWriteLine(message);
    }

    public override Encoding Encoding { get { return Encoding.UTF8; } }

    public override void WriteLine(string message)
    {
        Write(string.Format("{0}\n", message));
    }
 } 

Once we have this class we simply have to redirect the console out put by using the Console.SetOut command.

 writer = new TextBoxWriter();
writer.OnConsoleWriteLine += new Action<string>(writer_WriteHappened);
Console.SetOut(writer); Console.SetOut(writer); 

Simple, yet effective. I should get back to work :)