C# – How to implement tracing in .net

.net, c++, trace, vb.net

I am implementing a tracing mechanism myself. Now what I'd like to know is what is the best way to implement this mechanism(I mean, the architecture). First I thought of creating a class like this:

class Tracer {    public void NewEventRegistered(etc) {...} //this is the method I use to send this class the events I want to register    event newEventRegistered(..) //this is the event the user is going to use to catch all the events in the application that have been sent to NewEventRegistered method.}

But then I saw there is an TraceListener class that let's me implement Write and WriteLine methods. The big drawback is that both those methods allow only strings as arguments, and I'd want to be able to send a lot more info than strings. What should I do? Maybe my first ideia is the best?

edit: I do know there are a lot of tracing mechanisms like PostSharp and so, I'm just doing this for learning purposes!

Best Solution

The Write and WriteLine functions that accept strings only represent the minimum pair of functions you have to override. There are other write functions in TraceListener you can optionally override that accept objects.

TraceListener is, however, designed for use with the framework tracing functions. So if you're not going to use the class to "listen" to trace output going through the framework, you may be better off with an interface more suited to your particular tracing needs.

Perhaps inheriting from System.IO.TextWriter would be better for your case. It has many write methods, but I believe they route all their output through Write and WriteLine, so if you just override those two functions, you get a lot for free.