Author Archives: Edd

Console Logging with Microsoft Enterprise Library

I was having some issues formatting text with the Microsoft Enterprise Library using the .NET ConsoleTraceListener class. After some doing some research, it appears that a formatter for this class cannot be specified, at least, if one is it is ignored. The output of this listener is more akin to something that should be added to the event log and not very useful as feedback to the user, say, when they use a command line application. I didn’t want to use Console.WriteLine since, to me, that would defeat the purpose of having a single logging block and output to the console is a form of logging.

This post on StackExchange came to my rescue implementing a quick and simple custom trace listener to take the message and format it using the specified text formatter. This can then be configured on the endpoint as required during the application’s life-cycle without requiring a recompile.

I simplified it a bit to remove the colour formatting since I didn’t need it, resulting in this:

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using System;
using System.Diagnostics;

namespace EddPorter.Blog {

  [ConfigurationElementType(typeof(CustomTraceListenerData))]
  public class ConsoleTraceListener : CustomTraceListener {

    public override void TraceData(TraceEventCache eventCache,
        string source, TraceEventType eventType, int id, object data)
    {
      if (data is LogEntry && Formatter != null) {
        LogEntry le = (LogEntry)data;
        WriteLine(Formatter.Format(le));
      } else {
        WriteLine(data.ToString());
      }
    }

    public override void Write(string message) {
      Console.Write(message);
    }

    public override void WriteLine(string message) {
      Console.WriteLine(message);
    }
  }
}