Skip to content

Implementing a Logging Interface

Jon Wagner edited this page Mar 15, 2013 · 2 revisions

Implementing a Logging Interface

Since ESP can implement EventSource for you, let's just let it do all of the work for me and implement an interface. After all, a logging interface is just an interface, and we shouldn't care how it is implemented.

Let's convert our EventSource to an interface.

[EventSourceImplementation(Name="Calculator")]
public interface ICalculatorEventSource
{
	[Event(1, Message="Clear", Level=EventLevel.Informational)]
	void Clear();

	[Event(2, Message="Add {0} {1}", Level=EventLevel.Informational)]
	int Add(int x, int y);

	[Event(3, Message="Multiply {0} {1}", Level=EventLevel.Informational)]
	int Multiply(int x, int y);
}

// somewhere else in our code...
public static ICalculatorEventSource Log = EventSourceImplementer.GetEventSourceAs<ICalculatorEventSource>();

Notice a few things:

  • We kept the Event attributes on the methods, but had to change EventSource to EventSourceImplementation. Unfortunately, the EventSource attribute can't be applied to interfaces, so we had to add another one. The good news is that it works the same way as EventSource.
  • We moved our static instance out of the class. You are probably using Inversion of Control (IoC) anyway, right?
  • Note that the return values for Add and Multiply are no longer void. This lets us use the logging interface in other scenarios, such as mocking out a test component.

To log events, simply call the appropriate method on the log object:

Log.Add(1, 2);

That's it. ESP does the rest.

In fact, ESP fills in the Event Attributes for you, so you don't need to do that if you don't have a reason to define any of the values. We can rip them out and get the same results:

[EventSourceImplementation(Name="Calculator")]
public interface ICalculatorEventSource
{
	void Clear();
	int Add(int x, int y);
	int Multiply(int x, int y);
}

// somewhere else in our code...
public static ICalculatorEventSource Log = EventSourceImplementer.GetEventSourceAs<ICalculatorEventSource>();

Default Event Attribute Values

By default, if you do not specify an Event Attribute, ESP will do the following:

  • ID - one higher than the greatest ID in use.
  • Message - {0} {1}... one for each parameter on the method.
  • Level - informational unless overridden by the EventAttributeProvider.
  • OpCodes - none
  • Tasks - none
  • Keywords - ESP uses one bit per method, in the order they are declared. _Completed and _Faulted events share the same keyword as their invocation method.
Clone this wiki locally