Question

We have a custom TraceListener implementation which only logs when a specific object (LogMessage) is received. This all works well when using directly with the Trace.Write(object) method.

Due to Performance reason, I want to separate the Listener, so all non-relevant Trace messages are not passed to the listener. Therefore I created a specific TraceSource whith only this listener attached.

Now I struggle to pass my custom log object (LogMessage) to the listener using the TraceSource. The TraceSource.TraceData(TraceEventType, int, object) always invokes the TraceListener.Write(string) method, not the TraceListener.Write(object) method.

Is there any way I can pass the custom object to the Listener using the TraceSource?

Sample code:

using System.Diagnostics;

namespace Sample
{
    public class LogMessage
    {
        public byte[] Data { get; set; }
        //...
    }

    public class Sample
    {
        public void Foo()
        {
            var ts = new TraceSource("Test");

            var lm = new LogMessage();
            //lm.Data = ...;

            //this works: calls the Write(object) method in listener
            Trace.Write(lm);

            //this doesn't work: calls the Write(string) method in listener
            ts.TraceData(TraceEventType.Information, 0, lm);
        }
    }

    public class MyListener : TraceListener
    {
        public override void Write(string message)
        {
            //not in use
        }

        public override void WriteLine(string message)
        {
            //not in use
        }

        public sealed override void Write(object o)
        {
            if (o is LogMessage)
            {
                //do someting with the LogMessage
            }
        }
    }
}

Thanks Thomas

Was it helpful?

Solution

maybe it's too late for an answer but anyway :

By using a tool like JustDecompile you can easily see that TraceSource.TraceData uses TraceListener.TraceData method which itself basically calls WriteLine with object.ToString() for message.

So you'll have to override the ToString method for your class LogMessage in order to do as you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top