Search code examples
c#xamarin.ios

What's the recommended way to prefix Console.Write?


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.


Solution

  • 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();
        }
    }