Raising events from your applications

patterns & practices Developer Center

After you have created a custom event source class in your application, you use it to raise events that will be logged. This topic explains how to use your custom event source to raise events. For details of how to create an event source that defines the log messages you can write, see the topic Developing event sources using the .NET EventSource class.

All of the information required to generate the event, such as the identifier, level, keywords, message, and payload, are encapsulated in the custom event source class. Raising an event is simply a matter of calling the appropriate event method together with any required parameters.

The following code shows how to write a log message using the MyCompanyEventSource example class described in the topic Developing event sources using the .NET EventSource class. It raises the custom event named Startup, which requires no parameters.

MyCompanyEventSource.Log.Startup();

For event definitions that do take parameters, you must specify these when you raise the event in your application. For example, the following code shows how the Failure event is defined in the example MyCompanyEventSource class.

[Event(1, Message = "Application Failure: {0}", 
       Level = EventLevel.Critical, Keywords = Keywords.Diagnostic)]
internal void Failure(string message)
{
  if (this.IsEnabled()) this.WriteEvent(1, message);
}

To raise this event, the application code simply calls the method and provides the required parameter value, as shown in the following code.

MyCompanyEventSource.Log.Failure("Failed to start");

This raises the event with ID=1, with an event level of Critical, associated with the keyword Diagnostic, and with the error message Application Failure: Failed to start.

Next Topic | Previous Topic | Home | Community