0

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

Thomas Zweifel
  • 627
  • 1
  • 6
  • 19

1 Answers1

1

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.

Sylv21
  • 345
  • 2
  • 11
  • Thanks for your reply. I was not aware that by definition TraceListener.TraceData uses the ToString() method. But we need the passed object in the listener which then is casted back to the custom log message and sent to the log Server. Your information brought me to the idea to override the TraceListener.TraceData and handle the object in the override. I guess this will work and bring the solution to my problem. Will figure out after the Weekend. Many thanks! – Thomas Zweifel Apr 12 '13 at 15:56