Monday, 3 November 2014

Quick and easy Console Logging - Trace

trace

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 :) Thanks once again to

3 comments :

  1. An Obvious Extension point could be passing in the log output location to the Method call, but I wanted to keep it simple :)

    ReplyDelete
  2. I just wanted to point out that it looks as though you aren't using the variable "dir" you created in the second line of the function.

    ReplyDelete
    Replies
    1. yeah that looks to be the case. You could probably use it to set a logger location relative to the active directory though if you wanted.

      Delete