This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1+

Logging Messages in Event Logs

Microsoft Windows provides a built-in event logging system where informational messages, warnings, errors and audit details can be stored and viewed with the Event Viewer utility. This system is ideal for logging messages generated by a .NET application.

Creating a Custom Event Log

The previous examples used the standard application event log to hold the logged messages. Usually this is an acceptable storage location. However, sometimes you may wish to create your own log to hold messages for an application, a suite of programs or for all of the software developed by your company.

The process for creating a new event log requires a small modification to the code. When creating the new event source, rather than specifying "Application" as the event log parameter, you simply provide the name of the new log that you wish to create. The event log and event source are then created at the same time and bound together.

To demonstrate, modify the Main method code as follows. This sample will create a new event log named "My Event Log" and an associated event source named "My Sample Event Source 2". Three events will then be added to the log. After executing this program, refresh or reload the Event Viewer to examine your new log.

string eventLog = "My Event Log";
string eventSource = "My Sample Event Source 2";

if (!EventLog.SourceExists(eventSource))
    EventLog.CreateEventSource(eventSource, eventLog);

EventLog.WriteEntry(eventSource, "Information!", EventLogEntryType.Information);
EventLog.WriteEntry(eventSource, "Warning!", EventLogEntryType.Warning);
EventLog.WriteEntry(eventSource, "Error!", EventLogEntryType.Error);
31 August 2008