A simple C# example of writing to the Windows Application Event Log
Posted: (EET/GMT+2)
Today I needed to write some .NET code to write to the venerable Windows Event Log, and like you might know, this is pretty simple using the EventLog class and its WriteEntry method.
Here's an example that also registers the proper event source name before log entries can be written. Note that there must be a small delay (seconds) before the entry can be written if the event log source must be registered. In the below sample code, I'm using a simple Windows Forms MessageBox to cause a delay.
private void WriteEntryButton_Click(object sender, EventArgs e)
{
const string EventSourceName = "MyApp-MyEventLogSource";
const string EventLogName = "Application";
// make sure source exists
if (!EventLog.SourceExists(EventSourceName))
{
EventLog.CreateEventSource(EventSourceName, EventLogName);
MessageBox.Show($"New event log source has been created: {EventSourceName}.");
}
// write an entry to the log
EventLog logger = new EventLog()
{
Log = EventLogName,
Source = EventSourceName
};
logger.WriteEntry("Hello, World from C#!");
MessageBox.Show($"New event log entry successfully written to the \"{logger.Log}\" log.");
logger.Dispose();
}
Happy hacking!