Search code examples
c#.nettraceetw

How does System.Diagnostics.Tracing.EventSource.IsEnabled work?


When using a custom event source e.g.:

[EventSource(Name = "MyEventSource")]
public partial class CustomEventSource : EventSource
{
}

There is an IsEnabled method on the EventSource class:

EventSource.IsEnabled(eventLevel, eventKeywords)

https://msdn.microsoft.com/en-us/library/hh393402(v=vs.110).aspx

How does this method determine whether the event is 'Enabled' for the level and keywords? There doesn't seem to be any solid documentation on this. On my implementation the method is returning false and I am not sure what needs to be done in order to make it return true.


Solution

  • Seems like you need to attach an EventListener to your EventSource to enable it:

    class CustomEventListener : EventListener
    {
        protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
        }
    }
    
    void Main() 
    {
        var src = new CustomEventSource();
        var listener = new CustomEventListener();
        Console.WriteLine(src.IsEnabled(EventLevel.LogAlways, EventKeywords.None)); // false
        listener.EnableEvents(src, EventLevel.Error);
    
        Console.WriteLine(src.IsEnabled(EventLevel.LogAlways, EventKeywords.None)); // true
        Console.WriteLine(src.IsEnabled(EventLevel.Critical, EventKeywords.None)); // true
        Console.WriteLine(src.IsEnabled(EventLevel.Verbose, EventKeywords.None)); // false
    }
    

    EDIT:

    I also found the EvenSource.SendCommand method which can take EventCommand.Enable as an argument but that only throws an ArgumentException for me. Yes, the documentation for EventSource is really bad.