Search code examples
c#.netloggingsystem.diagnosticseventsource

Can't register listeners to System.Diagnostics.Tracing.EventSource


I have a component that is used by different applications. In this component we might need logging so I thought I'd use an EventSource.

The component is netstandard2.0, the application using the component is .NET Framework 4.6.1.

This is what I have so far in my component:

public class XEvents
{
    public const int BeforeSendingRequest = 1;
    public const int AfterSendingRequest = 2;
}

[EventSource(Name = "XEventSource")]
public class XEventSource : EventSource
{
    public static XEventSource Log = new XEventSource();

    [Event(XEvents.BeforeSendingRequest, Message = "Request: {0}", Level = EventLevel.Verbose, Keywords = EventKeywords.WdiDiagnostic)]
    public void BeforeSendingRequest(string request) { if (IsEnabled()) WriteEvent(XEvents.BeforeSendingRequest, request); }

    [Event(XEvents.AfterSendingRequestToCsam, Message = "Response: {0}", Level = EventLevel.Verbose, Keywords = EventKeywords.WdiDiagnostic)]
    public void AfterSendingRequest(string response) { if (IsEnabled()) WriteEvent(XEvents.AfterSendingRequest, response); }

}

And in the application I added the following to the app.config:

  <system.diagnostics>
    <sources>
      <source name="NamespaceOfEventSource.XEventSource" switchValue="Verbose">
        <listeners>
          <add name="XEventSourceListener" />
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="XEventSourceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="X.log" traceOutputOptions="ProcessId, DateTime" />
    </sharedListeners>
    <trace autoflush="true" />
  </system.diagnostics>

But when I run the application there is no X.log inside the bin folder. When I debug to the eventsource of the component I see that Enabled() returns false.

I suspect the listeners arent beeing bound to the EventSource. But I don't really see what I'm doing wrong.

Thanks in advance for any information you can give me!


Solution

  • I ended up using TraceSource instead of EventSource. https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.tracesource?view=netcore-3.1