How to write just message to debug output with Enterprise Library Logging?

前端 未结 2 780
北海茫月
北海茫月 2021-02-05 15:04

I want to implement logging with EntLib Logging and hook up two TraceListeners for category \"Debugging\". One will write those messages to file and other will output them to sy

2条回答
  •  后悔当初
    2021-02-05 15:48

    I found a nice walkthrough on MSDN: Creating a Custom Trace Listener

    It does exactly what I need. Here is a full code I ended up with:

    using System;
    using System.Diagnostics;
    using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
    using Microsoft.Practices.EnterpriseLibrary.Logging;
    using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
    using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
    
    namespace Common.Utils
    {
        [ConfigurationElementType(typeof(CustomTraceListenerData))]
        public class FormattedDebugWriterTraceListener : CustomTraceListener
        {
            public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
            {
                if (data is LogEntry && this.Formatter != null)
                {
                    this.WriteLine(this.Formatter.Format(data as LogEntry));
                }
                else
                {
                    this.WriteLine(data.ToString());
                }
            }
    
            public override void Write(string message)
            {
                Debug.Write(message);
            }
    
            public override void WriteLine(string message)
            {
                Debug.WriteLine(message);
            }
    
        }
    }
    

    Configuration file:

    
    
      
        

    And the usage goes like this:

    Debug.Write("Debug.Write test");
    Logger.Write("EntLib test", "Debugging");
    

    Both end up in debug output easily traceable by DbgView.

提交回复
热议问题