Search code examples
c#event-logeventlog-source

Is it possible to specify an event category for Windows EventLogs in code?


I am looking for a way not to use Message Files, as I don't want the mess that comes with it.

I would like to be able to write events using a method similar to

public void WriteEvent(EventLogEntryType type, string description, int eventId, int categoryId)

And specify those categories in the same class I register my EventSource, in some enum.

Thanks!


Solution

  • Unfortunately this is not possible.

    Even thought things have changed a bit in terms of API, since that blog post I mentioned, yet the principe stayed the same. See the documentation + samples:

    https://msdn.microsoft.com/en-us/library/650k61tw(v=vs.100).aspx

    https://msdn.microsoft.com/en-us/library/system.diagnostics.eventinstance.categoryid(v=vs.100).aspx

    https://msdn.microsoft.com/en-us/library/system.diagnostics.eventloginstaller.categoryresourcefile(v=vs.100).aspx

    I found an acceptable workaround for this; use a different source id, instead of categoryId. It is simpler and can be done with simple API.

    Example: Manage event sources on your own, create event sources per category type. Use some lazy creation logic, e.g by running

    if (!EventLog.SourceExists(sourceName))
    {
        lock (_eventSourceCreationLock)
        {
            if (!EventLog.SourceExists(sourceName))
            {
                EventLog.CreateEventSource(sourceName, _logName);
            }
        }
    }
    

    And then, use this to write each log entry per source:

    EventLog.WriteEntry(sourceName, description, type, id);
    

    These samples are thread safe as well, as the static calls create a new internal event log.

    Instance methods of EventLog aren't guaranteed to be thread safe.