Home > Software engineering >  Write to Application EventLog in C#
Write to Application EventLog in C#

Time:05-20

I would like to write a custom source in the Event Viewer, for a number of different events.

I'd like to have the log name to just be "Application" and source to be "DDG ServiceWare". I looked at the documentation on MSDN and made this:

    private static void _writeToApplicationEventLog(string logMessage, int eventID)
    {
        if(!EventLog.SourceExists("DDG ServiceWare"))
        {
            EventSourceCreationData exitEvents = new EventSourceCreationData("DDG ServiceWare", "Application");
            EventLog.CreateEventSource(exitEvents);
        }

        using (EventLog eventLog = new EventLog("Application"))
        {
            eventLog.Source = "DDG ServiceWare";
            eventLog.WriteEntry(logMessage, EventLogEntryType.Error, eventID);
        }
    }

However, when I run it I get an exception saying:

An unhandled exception of type 'System.ArgumentException' occurred in System.dll The source 'DDG ServiceWare' is not registered in log 'Application'. (It is registered in log 'DDG ServiceWare'.) " The Source and Log properties must be matched, or you may set Log to the empty string, and it will automatically be matched to the Source property.

It doesn't change even if I change EventSourceCreationData exitEvents = new EventSourceCreationData("DDG ServiceWare", "Application"); to EventSourceCreationData exitEvents = new EventSourceCreationData("DDG ServiceWare", "DDG ServiceWare");

What am I doing wrong here?

CodePudding user response:

You may want to consider a package like SeriLog which will make logging much easier (not just to event logs but to files and other destinations). Have a look at this enter image description here

  • Related