Search code examples
c#event-vieweretw-eventsource

Microsoft TraceEvent - How to log to the Event Viewer


Using the Microsoft.Diagnostics.Tracing EventSource library (not to be mistaken for the System.Diagnostics.Tracing), it is possible to log certain messages to the event viewer by adding an Attribute to the Event annotation called 'Channel'. However this dumps the output to the 'Windows Logs\Application' area. How can I get this to log to 'Applications and Service Logs\MyApp\MyFeature' ?

Example code:

[EventSource(Name = "MyDemoApp")]
   public sealed class MyDemoEventSource : EventSource
   {
      private MyDemoEventSource () { }
...    
public const EventTask MyDemoTask = (EventTask) 12345;
...

[Event(12345,
     Message = "My Demo Error: {0}",
     Level = EventLevel.Warning,
     Channel = EventChannel.Admin,
     Task = Tasks.MyDemoTask,
     Keywords = Keywords.Rule,
     Opcode = Opcodes.Fail)]
    private void SomethingWentWrong(string ErrorMessage)
    {
        WriteEvent(12345, ErrorMessage);
    }

Solution

  • With thanks to Matthew Watson for pointing me in the direction of this article, the solution to the problem is contained within:

    https://blogs.msdn.microsoft.com/dotnet/2014/01/30/microsoft-diagnostics-tracing-eventsource-is-now-stable/

    *Remember to register your EventSource as this is the step that actually creates the entries in the Event Viewer, a unique name is required (if your company/product already has an entry in the Event Viewer for other purposes make sure you use a new name).