November 04, 2014
Quick and easy Console Logging - Trace
Legacy blog post from blogger platform about easy console logging with trace
This post is outdated and only exists for historical reasons
Just a quick Blog
I was wanting to get the output of my Console Write to a log file but still show to the Console!! So off to google I went and I found this amazing solution via StackOverflow!
I thought that I would pass on the love with a slightly modified (cleaned up and simplified the output location)
/// <summary>/// Initiates a Tracer which will print to both/// the Console and to a log file, log.txt/// </summary>private static void InitiateTracer(){Trace.Listeners.Clear();var dir = AppDomain.CurrentDomain.BaseDirectory;var twtl = new TextWriterTraceListener("log.txt"){Name = "TextLogger",TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime};var ctl = new ConsoleTraceListener(false) { TraceOutputOptions = TraceOptions.DateTime };Trace.Listeners.Add(twtl);Trace.Listeners.Add(ctl);Trace.AutoFlush = true;}
The next step is to use replace (ctrl+h) on "Console.Write(
" with "Trace.Write(
"
and "Console.WriteLine(
" with "Trace.WriteLine('. After this it probably will not build,
that will be because you need to add "
using System.Diagnostics;`"
to the top of the pages where you replace Console with Trace. The next error you might get is a bit less likely.
If you have been using Console.WriteLine's build in String.Format you will have to add String.Format
yourself as Trace doesn't do it automagically :(
Then simply call InitiateTracer() from within your Console Applications main and voilà you have your normal console output + output to a log.txt file in the same path as your executable so you can check over your logs at a later time!
Hope this helps :)