-
Notifications
You must be signed in to change notification settings - Fork 20
Implementing an EventSource
We saw how to implement an EventSource manually in .NET. Let's let ESP do it's magic and implement most of it for us.
The first thing to do is to declare your class as abstract. This lets you mark all of your methods as abstract and ESP will code them for you.
[EventSource(Name="Calculator")]
public abstract class CalculatorEventSource : EventSource
{
[Event(1, Message="Clear", Level=EventLevel.Informational)]
public abstract void Clear();
[Event(2, Message="Add {0} {1}", Level=EventLevel.Informational)]
public abstract void Add(int x, int y);
[Event(3, Message="Multiply {0} {1}", Level=EventLevel.Informational)]
public abstract void Multiply(int x, int y);
public static CalculatorEventSource Log = EventSourceImplementer.GetEventSourceAs<CalculatorEventSource>();
}
Notice a few things:
- We kept the attributes on the class in the same place. ESP will copy them to the implementation class for you.
- We removed the Keywords. If you don't specify any keywords, ESP will create one keyword per method automatically. (If you want to customize your keywords, see Controlling Logging Details Through Attributes).
Since this is an abstract class, we can't instantiate it directly, but we can get an instance from ESP:
public static CalculatorEventSource Log = EventSourceImplementer.GetEventSourceAs<CalculatorEventSource>();
ESP will build a derived class for you and automatically implement the abstract members for you. The methods all look like this:
if (IsEnabled(level, keyword))
WriteEvent(eventID, parameters);
You should never have to code this yourself.
If you want to log events in your application, typically you will create one static instance of the event source. (In fact if you try to create more than one instance, EventSource will throw an exception, so ESP can manage singletons for you.)
To log events, simply call the appropriate method on the log.
CalculatorEventSource.Log.Add(1, 2);
That's it. ESP does the rest.
Using ESP to implement EventSource makes it much easier and less error-prone. You can even pass in complex objects and they will be serialized as JSON to your log. (See Controlling Object Serialization for more details.)
With ESP, there is really no reason why your logging interface needs to be derived from EventSource. Let's take a look at Implementing a Logging Interface.