Writing to the Windows Event Log with C# .NET
October 13, 2017 1 Comment
In this post we saw how to create and delete event logs. We’ve also seen a couple examples of writing to the event log. Here come some more examples.
Say you want to send a warning message to the System log:
string source = "DemoSourceWithinApplicationLogSystem"; EventLog systemEventLog = new EventLog("System"); if (!EventLog.SourceExists(source)) { EventLog.CreateEventSource(source, "System"); } systemEventLog.Source = source; systemEventLog.WriteEntry("This is warning from the demo app to the System log", EventLogEntryType.Warning, 150);
As there is no such source yet in any event log it must be registered first. In the CreateEventSource method you can specify which log the source will belong to. The WriteEntry method has 5 overloads, of which you can see one above with a message, an entry type and an event ID. The event ID is an arbitrary integer that you can specify. It is an optional parameter which is set to 0 by default. The warning occurs like this in the event viewer:
Say you’d like to send a warning message to the Application log instead with no event ID:
string source = "DemoSourceWithinApplicationLog"; string log = "Application"; if (!EventLog.SourceExists(source)) { EventLog.CreateEventSource(source, log); } EventLog.WriteEntry(source, "This is a warning from the demo log", EventLogEntryType.Warning);
Here it is:
If you know that the source has already been registered then you can send a message in a shorter format:
string source = "DemoSourceWithinApplicationLog" EventLog.WriteEntry(source, "This is an error messsage from the demo log", EventLogEntryType.Error, 100);
You can view all posts related to Diagnostics here.
I have a application that my dev team put out that is configured this way. Although the only way we can get the log into event viewer is to be local admin on the application server. Any ideas?