BlackWasp
Windows Forms Programming
.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.

Event Logging System

There are many occasions when you will want to log messages to describe the current status of your application. During development, you may log events to assist in debugging complex problems. For applications that have no user interface, such as Windows services or application plug-ins, a log of events may be your only visibility of the activities performed. In live systems, event logs can help you to understand and resolve user support requests.

Each of these scenarios requires a method of storing structured messages and a means of viewing those messages at a later time. This is the purpose of the event logging system provided by Microsoft Windows. The system allows events to be stored centrally within a set of pre-configured or custom event logs.

Standard Logs

The Windows event logging system separates messages into event logs, each holding a timestamped list of logged items. Three standard logs are available on versions of the operating system from Windows NT 4.0 onwards:

  • Application Log. This log is used to store messages produced by application software that has been installed by the user. This is the preferred target log for events generated by your .NET programs if you wish to use a built-in log.
  • System Log. The system log is used to hold operating system events. These events provide information relating to built-in services, components and drivers. You can create events in this log from a .NET program but should carefully consider whether this is appropriate.
  • Security Log. This log records security events, such as failed attempts to log into Windows or firewall issues. This log cannot be written to using the methods described in this article.

There can be many more logs in addition to the application, system and security logs. Some may be defined by newer versions of Windows and some by installed applications. These can include event logs that you have created yourself using the methods described later in this article.

Message Types

There are five different types of event that can be added to an event log. Each has a particular meaning that should be considered when you log your own messages:

  • Error. Indicates a significant problem or failure. This may signify that data was lost or that functionality failed to execute.
  • Warning. Signals a problem that is less significant than an error. Warnings are often used to highlight a condition that has the potential to become a problem, such as low disk space or memory, or an issue that was overcome automatically but that should be investigated.
  • Information. This type of message is commonly used to log successful activities that do not require any intervention. For example, you may log an informational message to indicate that a batch process was completed.
  • Success Audit. Denotes a successful audited security access attempt. Success audits are used extensively in the security log to indicate, for example, a successful logon attempt. This type of message is uncommon in application logs.
  • Failure Audit. A failure audit event describes an unsuccessful audited security access attempt. This type of message is uncommon in application logs.

The Event Viewer

To view the centralised set of event logs and the messages contained within, you use the Event Viewer application. This tool can be found in the Administrative Tools section of the Control Panel.

Windows XP Event Viewer

The above diagram shows a sample of the Event Viewer from Windows XP. In later operating systems, such as Vista, the layout of the window is quite different although the basic elements are the same. To the left is a hierarchical list of all of the event logs registered in the operating system. In the figure above you can see the three standard logs and an additional application-specific log for Internet Explorer.

The right side of the window shows the individual events that have been created in the currently selected log. The events are displayed in a grid with columns that identify information such as the type of message logged, the date and time at which the event was created and the event source. The event source is a named source that usually represents a single application or module within a system. To see the full text of a logged message, you can double-click it.

The Event Logger provides many options for viewing, filtering, saving and clearing logs. However, these are beyond the scope of this article.

Logging Events

In the remainder of this article we will demonstrate some of the methods available for logging events in an event log. If you wish to follow the examples, create a new console application and use the Main method to try the sample code. As the classes used in the examples are within the System.Diagnostics namespace, you should add the following line at the top of the class containing the Main method:

using System.Diagnostics;

Registering an Event Source

As we have seen, when an event is logged it is associated with an event source. The source appears in the list of events in a log, making it easier to filter and sort events based upon their source. For a source to be used correctly, it must first be registered with the operating system and associated with a specific event log. This is achieved using the CreateEventSource method of the EventLog class. This static method requires two parameters that specify the names of the event source and the associated log respectively.

We can create a sample event source named "My Sample Event Source" and link it to the Application log by adding the following commands to the Main method:

string eventSource = "My Sample Event Source";
EventLog.CreateEventSource(eventSource, "Application");

If you execute the program in its current form, the event source will be created. However, if you run the program a second time you will receive an ArgumentException. This exception occurs because you may not create the same event source twice. Luckily, you can check for the existence of an event log before trying to create it to avoid this error. To do so, you use the SourceExists method, passing the name of the event source to check for.

Change the contents of the Main method to that shown below to avoid the exception:

string eventSource = "My Sample Event Source";

if (!EventLog.SourceExists(eventSource))
    EventLog.CreateEventSource(eventSource, "Application");

Security Concerns

If you executed the above code using Microsoft Vista or a newer operating system, you are likely to have seen an exception similar to the following:

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security.

This problem occurs due to new code access security restrictions introduced in Microsoft Vista. To prevent unauthorised code from viewing or making changes to the operating system configuration, the SourceExists and CreateEventSource methods cannot be executed by a standard user. In order to try the samples, you must compile the code and run it by right-clicking the resultant executable file and selecting "Run as administrator".

In a production environment this causes the problem of ensuring the availability of an event log source before trying to log messages. Unless you can guarantee that your application will only run on platforms without this security restriction, you should not create event log sources from within the main program. You should certainly not require that your program has administrative privileges as this raises other serious security concerns.

If your program is for a limited audience and you will be manually configuring the software, you should create a second program that simply creates the required event sources. This program can be executed once using the "Run as administrator" option. Once the event sources have been generated, the main application can be executed without administrative rights.

If you are distributing your application using a setup package and have no control over the target machine, you should add a custom action to your installation routine. As setup packages generally require administrative privileges to complete successfully, your custom action can use the EventLog methods described above to create the event source during installation. The main application can then use the event source without being executed by an administrator.

Logging an Event

Now that we have an event source to work with, we can log an event. To do so you use the WriteEntry method of the EventLog class. This method includes ten overloaded variations including static implementations and versions that require an object instance. In this article we will use two of the static overloads. The first requires two string parameters specifying the event source and the message to store.

Add the following code to the end of the Main method and execute it:

EventLog.WriteEntry(eventSource, "This is my first event!");

To view the results, open the Event Viewer program or, if it is already open, refresh the Application log. You should see a new entry in the list with a source of "My Sample Event Source". Double-click the message to see the contents.

When using this simple method signature, the type of the logged message is always "Information". If you wish to change the type to one of the other four options, you can add a third parameter to the WriteEntry method. This parameter accepts a value of the EventLogEntryType enumeration, which has a constant value to represent each of the five available message types.

Remove the previous WriteEntry line from the Main method and replace it with the following code. Execute the program to see message of other types in the application log.

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

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);
Link to this Page31 August 2008
RSS RSS Feed