Search code examples
c#event-logevent-viewer

Writing to the event log with hierarchy


I know there are a lot of topics about writing to the event viewer on SO, but I didn't find what I need.

I have the following code to create a new Event Log Category in the event Viewer:

string sSource = "MyWebService";
string sLog = "My Application";
string sMsg = "Error Message Goes here";

if (!EventLog.SourceExists(sSource))
{ EventLog.CreateEventSource(sSource, sLog); }

This works as expected and in the Event Viewer, I have the following output:

enter image description here

So, writing to the event viewer is not a problem, but the problem occurs when I want to create some hierarchy in the logs.

So, let's assume that I've written an application that consists out of various components:

- MVC
- Web API
- Windows Service

Then in the Event Viewer, I want to create a dictionary that contains all those elements just as Microft does:

enter image description here

This means I would like to have an output that looks like:

- Application (directory)
    - MVC (directory)
        - Others (logs)
    - Web API (directory)
        - Demo (logs)
    - Windows Service (directory)
        - Authentication (logs)

I've tried to do the following:

string sSource = "MyWebService";
string sLog = "My Application";
string sMsg = "Error Message Goes here";

if (!EventLog.SourceExists(sSource))
{ EventLog.CreateEventSource(sSource, sLog); }

if (!EventLog.SourceExists(sLog))
{ EventLog.CreateEventSource(sLog, "Web Service"); }

But of course, this didn't work.

Anyone knows a how to create a hierarchical structure in the Event Viewer?

Important to say: I like to have full control over my code, so I don't wan't to use any third-party libraries.


Solution

  • To do what you want you need to use Event Tracing for Windows (ETW). In .NET you can use the EventSource class but there is a more up to date NuGet package that I suggest you use: Microsoft EventSource Library. There is also a NuGet package with samples which should provide a good starting point if you are new to ETW.

    In addition to creating code that writes to the event log you need to create a manifest and an associated resource DLL. The NuGet package has a tool that automates this process based on the log events that you have created in code. You then need to register the event source using the wevtutil command line tool.