This project has moved. For the latest updates, please go here.

Log4Net Trace Listener

Jan 25, 2010 at 3:53 PM

I have found this class useful for incorporating the messages that come from System.Diagnostics.Trace into my Log4Net logs so that I can see the events in Log2Console.


public class Log4netTraceListener : System.Diagnostics.TraceListener {
        private static Dictionary<string, ILog> _Loggers = new Dictionary<string, ILog>();
        private string messageSoFar = String.Empty;

        public override void Write(string message) {
            messageSoFar += message;

        public override void WriteLine(string message) {
            string completeMessage = messageSoFar + message;

            ILog log;

            // Get or create a logger for this TraceSource
            if (_Loggers.ContainsKey(Name)) {  
                log = _Loggers[Name];
            } else {
                log = LogManager.GetLogger(Name);

            // Strip out TraceSource name from message and log
            messageSoFar = String.Empty;

Don't forget to configure the Listeners in your config file.  I use this for CAB and require the following setup,  your setup will vary!


			<source name="Microsoft.Practices.ObjectBuilder" switchValue="Verbose">
					<add name="Microsoft.Practices.ObjectBuilder" type="Tavis.Framework.Tools.Log4netTraceListener, TavisFramework"/>
			<source name="Microsoft.Practices.CompositeUI.Commands.Command" switchValue="Verbose">
					<add name="Microsoft.Practices.CompositeUI.Commands.Command" type="Tavis.Framework.Tools.Log4netTraceListener, TavisFramework"/>

			<source name="Microsoft.Practices.CompositeUI.WorkItem" switchValue="Verbose">
					<add name="Microsoft.Practices.CompositeUI.WorkItem" type="Tavis.Framework.Tools.Log4netTraceListener, TavisFramework"/>