Search code examples
c#.neteventsrecordevent-log

C# Getting the right event level from EventRecord.Level


I included a event viewer in my application, where the user can see a list of events from the Windows Event Log caused by the application with details, event ids, sources etc.

Now there's one small problem I have: Like in the Event Viewer from windows, I want to show a little icon in front of the list entry based on the level of the event (Information, Warning, Error/Critical).

In the code behind, I get all my information from an EventLogReader that returns a list of EventRecords. Regarding the level, these EventRecords expose two properties: Level and LevelDisplayName. Since the LevelDisplayName is culture dependent, I have to work with the Level - which is a byte? type.

How do I get the right level from this? I know there's a StandardEventLevel enum but I don't know if you can match this to the Level and if yes, how to convert it. I'm imagining something like this:

switch (__eventRecord.Level)
            {
                case(StandardEventLevel.Informational):
                    __level = "Information";
                    break;
                case(StandardEventLevel.Warning):
                    __level = "Warning";
                    break;
                case(StandardEventLevel.Error):
                case(StandardEventLevel.Critical):
                    __level = "Error";
                    break;
            }

Has anyone an idea how to approach this in the right way?


Solution

  • Welp, I thought a simple cast - (StandardEventLevel)__eventRecord.Level - didn't work, since sometimes I didn't seem to get a result in the switch case. Turns out there was something wrong in the logging and it recorded some events as 'LogAlways' or level 0. So just cast it and it works.