14

I'm looking for a way to insert a prefix (date and time) to every Console.Write[Line]. I'm looking for a recommended way to do so, just like the recommended way for changing the output is to use Console.SetOut.

I'm well aware that I can do String.Format("{0} {1}", DateTime.Now, msg), but I'm trying to leave that as my last resort.

The problem is that the output is changeable at run time, and the default one already appends the current time. If I append it on my code I will duplicate the date.

Is there such a thing? I'm using Monotouch, so I can only use libraries compiled for it.

Jonas Stawski
  • 6,682
  • 6
  • 61
  • 106

2 Answers2

17

You need to inherit from System.IO.TextWrite, provide an Encoding and overrides for e.g. WriteLine and Write. Store the original Console.Out before changing with Console.setOut(x).

Here's a complete code example:

class PrefixedWriter : TextWriter
{
    private TextWriter originalOut;

    public PrefixedWriter()
    {
        originalOut = Console.Out;
    }

    public override Encoding Encoding
    {
        get { return new System.Text.ASCIIEncoding(); }
    }
    public override void WriteLine(string message)
    {
        originalOut.WriteLine(String.Format("{0} {1}", DateTime.Now, message));
    }
    public override void Write(string message)
    {
        originalOut.Write(String.Format("{0} {1}", DateTime.Now, message));
    }
}

class Program
{
    static void Main(string[] args)
    {
        Console.SetOut(new PrefixedWriter());
        Console.WriteLine("test 1 2 3");
        Console.ReadKey();
    }
}
ChristopheD
  • 112,638
  • 29
  • 165
  • 179
  • That's the best way. MonoTouch 5.3+ redirect the `Console.Write*` to `NSLog` to work around the **stdout** limitation Apple added in iOS 5.1. The preliminary version of the source code is available on my blog: http://spouliot.wordpress.com/2012/03/13/ios-5-1-vs-stdout/ – poupou Apr 26 '12 at 21:22
  • Love how it nicely integrates and solves the problem with double dates mentioned in the question – Jonas Stawski Apr 27 '12 at 18:37
8

You could just replace the Console call with your own class.

class MyConsole
{
   public static void WriteLine(string msg)
   {
      Console.Write(String.Format("{0} {1}", DateTime.Now, msg));
   }
}

Then of course, all calls to Console.Write become MyConsole.Write.

You could also take it a step further and alias Console with MyConsole in all code files...

using Console = MyNamespace.MyConsole;
Steve Danner
  • 21,818
  • 7
  • 41
  • 51