Event Logging C# Help

The system administrator uses the Event Viewer to get critical and warning information about the system and applications. Youshould write error messages from your application to the event log so that the information can be read with the Event Viewer. Trace messages can be written to the event log if you configure the EventLogTraceListener class. The EventLogTraceLi~tener has an EventLog object associated with it to write the event log entry. You can also use the EvEmtLogclass directly to write and read event logs

In this section, you explore the following:

¤  Event-logging architecture

¤ Classes for event logging from the System. Diagnostics namespace

¤ Adding event logging to services and to other application types

¤  Creating an event log listener with the EnableRaisingEvents property of the EventLog class

shows an example of a log entry from a modern.

Figure 18-3

Figure 18-3

For custom event logging, you can use classes from the Sys tern. Diagnos tics namespace.

Event-Logging Architecture

The event log information is stored in several log files. The most important ones are application, security, and system. Looking at the registry configuration of the event log service, you will notice several entries under HKEY_LOCAL_MACHINE\System\CurrentControlSet \Services \Eventlog with configurations pointing to the specific files. The system log file is used from the system and device drivers. Applications and services write to the application log. The security log is a read-only log for applications. The auditing feature of the operating system uses the security log. Every application can also create a custom category and log file to write event log entries there. For example, this is done by Windows OneCare and Media Center.
You can read these’ events by using the administrative tool Event Viewer. The Event Viewer can be started directly from the Server Explorer of Visual Studio by right-clicking the Event Logs item and selecting the Launch Event Viewer entry from the context menu. The Event Viewer is shown in In the event log, you can see this information:

¤  Type – The type can be Information, Warning, or Error. Information is an infrequent successful operation; Warning is a problem that is not immediately significant; and Error is a major problem. Additional types are FailureAudit and SuccessAudit, but these types are used only for
the security log.

¤   Date – Date and TIme show the time when the event occurred.



¤ Source – The Source is the name of the software that logs the event. The source for the application log is configured in:

¤ Below this key, the value EventMessageFile is configured to point to a resource DLL that holds error messages.

¤ Event identifier – The Event identifier specifies a particular event message.

Event-LC?gglng Classes

The System. Diagnosticsnamespace has some classes for event logging, which are shown in the following table.

The heart of event logging is in the EventLog class. The members of this class are explained in the following table.

Creating an Event Source

Before writing events, you must create an event source. You can use either the CreateEventSource () method of the EventLog class or the class EventLoglnstaller. Because you need administrative privileges when creating an event source, an installation program would be best for defining the new source.

Deployment,” explains how to create installation programs.

The following sample verifies that an event log source named EventLogDemoApp already exists. If it doesn’t exist, an object of type EventSourceCreationDa ta is instantiated that defines the source name EventLogDemoApp and the log name ProCSharpLog. Here, all events of this source are written to the ProCSharpLog event log. The default is the application log

 The name of the event source is an identifier of the application that writes the events. For the system administrator reading the log, the information helps in identifying the event log entries to map them to
application categories. Examples of names for event log sources are LoadPerf for the performance monitor, MSSQLSERVERfor Microsoft SQL Server, Msilnstaller for the Windows Installer, Winlogon, Tcpip, Time-Service, and so on.

Setting the name Application for the event log writes event log entries to the application log. You can also create your own log by specifying a different application log name. Log files are located in the directory <windows>\System32 \WinEvt \Logs.

With the EventSourceCreationData, you can also specify several more characteristics for the event log, as shown in the following table

Writing Event Logs

For writing event log entries, you can use the WriteEntry() or WriteEvent () methods of the EventLog class. The EventLog class has both a static and an instance method wri teEntry (). The static method
WriteEntry () requires a parameter of the source. The source can also be set with the constructor of the EventLog class. Here in the constructor, the log name, the local machine, and the event source name are defined. Next, three event log entries are written with the message as the first parameter of the WriteEntry () method. WriteEntry () is overloaded. The second parameter you can assign is an enumeration of type EventLogEntryType. With EventLogEntryType, you can define the severity of the event log entry. Possible values are Information, Warning, and Error, and for auditing SuecessAudi t and FailureAudi t. Depending on the type, different icons are shown in the Event Viewer. With the third parameter, you can specify an application-specific event ID that can be used by tlu. application itself. In addition to that, you can also pass application-specific binary data and a category.

Resource Files

Instead oi defining the messages for the event log in the C# code and passing it to the WriteEntry ( ) method, you can create a message resource file, define messages in the resource file, and pass message identifiers to the WriteEvent () method. Resource files also support localization

Message resource files are native resource files that have nothing in common with .NET resource files.NET resource files are covered in Chapter 21, “Localization.”

A message file is a text file with the mefile extension. The syntax that this file uses to define messages is very strict. The sample file EventLogMessages .me contains four categories followed by event messages. Every message has an ID that can be used by the application writing event entries. Parameters that can be passed from the application are defined with’ syntax in the message text.


Database Query

Data Update.

Network Communication

MessageId = lOOP
Severity = Success
Facility = Application
SymbolicName = MSG_CONNE~T_1000
Connection successful

MessageId = 1001
Severity = Error
Facility = Application
SymbolicNam~ = MSG_CONNECT_FAILED_1001
Could not connect to server %1.

Messageld = 1002
Severity = Error
Facility = Application
SymbolicName = MSG_DB_UPDATE_1002
Language=English .
Database ~pdate failed.

Messageld = 1003
Severity = Success
Facility = Application
SymbolicName = APP_UPDATE
Application %%5002 updated.

Messageld = 5001
Severity = Success
Facility = Application
Professional C* Sample Event Log

Messageld = 5002
Severity = SucCess
Facility = Application

Use the Messages Compiler, mc .exe, to create a binary message file.mc -s EventLogDemoMessages .mc compiles the source filecontaining the messages to a messages filewith the .bin extension and the fileMessages. rc, which contains a reference to the binary message file:

-s EventLogDemoMessages.mc

Next, you must use the Resource Compiler, rc: exe. rc EventLogDemoMes~ages. rc creates the resource fileEventLogDemoMessages .RES:

rc EventLogDemoMessages.rc

With the linker,you can bind the binary message fileEventLogDem.oMessages. RES to a native DLL: link lOLL ISUBSYSTEM:WINDOWS INOENTRY IMACHlNE:x86 EventLogDemoMessages.RES

Now, you can register an event source that defines the resource files as shown in the following code. • First, a check is doneif the event source named EventLogDemoApp exists. If the event log must be
created because it does not exist, the next check verifies if the resource file is available. Some samples in the MSDN documentation demonstrate writing the message file to the <windows>\system32 directory. but you shouldn’t do that. Copy the message DLL to a program-specific directory that you can get with the SpeeialFolder enumeration value ProgramFi les. If you need to share the messages file among multiple applications, you can put it into Environment. SpedalFolder. CommonProgramFiles. If the file exists, a new object of type EvetltSoureeCreationData is instantiated. In the constructor, the name of the source and the name of the log are defined. You use the properties CategoryResoureeFile, MessageResourceFi1e, and ParameterResourceFile to define a reference to the resource file. After the event source is created, you can find the information on the resource files in the registry with the event source. The method CreateEventSource registers the new event source and log file. Finally, the method RegisterDisplayName () from the EventLog class specifies the name of the log as it is displayed in the Event Viewer. The ID 5001 is taken from the message file.

If you want to delete a previously created event source, you can do so with EventLog . DeleteEventS ouree (sourceName) ;. Todelete a log, you can invoke EventLog . Delete (logName) ;.

EventLog evLog = new EventLog(logName •.•.•• sourceName);
evLog.RegisterDisplayName(resoureeFile. 5001)

Now, you can use the wri teEvent () method instead of Wri teEntry () to write the event log entry. WriteEvent () requires an object of type Eventlnstanee as parameter. With the Eventlnstanee, you can assign the message IO, the category, and the severity of type EventLogEntryType. In addition to the Eventlnstanee parameter, WriteEvent () accepts parameters for messages that have parameters and binary data as byte array.

EventLog log = new EventLog(logName. sourceName);
Eventlnstance info1 = new Eventlnstance(lOOO. 4.
EventInstance info2 = new EventInstance(l001. 4.
1og.WriteEvent(info2. “avalon”);
Eventlnstance info3 = new Eventlnstance(1002. 3.
byte[] addionallnfo = { 1. 2. 3 };
log.WriteEvent(info3. addionallnfo);

For the message identifiers. it is useful to define a class with const values that provide a more meaningful name for the identifiers in the application.

You can read the event log entries with the Event Viewer

Event Log Listener

Instead of using the Event Viewer to read event log entries. you can create a custom event log reader that listens for events of specified types as needed. You can create a reader where important messages pop up to the screen. or send SMS to a system administrator.

Next. you write an application that receives an event when a service encounters a problem. Create a simple Windows application that monitors the events of your Quote service. This Windows application
consistaof a list box and an Exit button only. as shown in Figure 18-5.

Figure 18-5

Figure 18-5

Add an EventLog component to the design view by dragging and dropping it from the toolbox. Set the Log property to Appl ication. You can set the Source property to a specific source to receive event log
entries from only this source; for’ example the source EventLogDemoApp for receiving the event logs from the application created previously. If you leave the Source property empty. you will receive

events from every source.You also need to change the property EnableRaisingEvents. The default value is false; setting it to true means that an event is generated each time this event occurs, and you
can add an event handler for the EntryWritten event of the EventLog class. Add a handler with the V•name OnEntryWritten () to this event.
The OnEntryWritten() handler receives an EntryWrittenEventArgs object as argument, from which you can get the complete information about an event. With the Entry property, an EventLogEntry object with information about the time, event source, type, category, and so on is returned:

The running application displays event log information, as shown



Posted on November 3, 2015 in Tracing and Events

Share the Story

Back to Top