I wonder what the best approach is in implementing a logger which essentially eats all Console.WriteLine() messages and spits out a text file of all these messages.
I know I could use a StringBuilder and populate it with all the messages by doing .AppendLine wherever Console.WriteLine occurs…but I am looking for something more magical than that. Some way using which I don’t have to write as many lines of code as Console.WriteLines in existing code.
And in case you missed the tags, this is for a C#4.0 console application.
I assume what you want is a stream that writes to standard out and to a file. That is, you want everything to still show up on the console, but you also want it to be written to a file. (If you just wanted to redirect output to a file, you could do that from the command line.)
You need to create your own
TextWriter-derived class, and have it do the actual output. You callConsole.SetOutto make the console write to yourTextWriter.And in the program that uses this:
You don’t have to override all the
TextWritermethods. As the documentation says, “A derived class must minimally implement theTextWriter.Write(Char)method to make a useful instance ofTextWriter.”I’ve done something similar to this, and it works quite well.