How Do I...Write to an event log?
Event logging provides a standard, centralized way for
your applications to record important software and hardware events.
Windows supplies a standard user interface for viewing the logs (the Event Viewer). Using the common language runtime's EventLog component, you can easily connect to existing event logs on a local computer, and write entries to
these logs. You can also read entries from existing logs and create your own
custom event logs.
This sample illustrates how to write to an event log. It's a
small console application that can be run from a command prompt. The
application takes three command line arguments. The first argument is the log
to which the application will write. The second is the message to be written.
The third is the name of the source of the event log entry (message).
Try running the sample as follows:
> LogWrite.exe MyLog "Hello World!" "LogWrite Sample"
Now, open the event log viewer and observe that there is a
new log added to the list of logs on your machine. The log's name is "MyLog"and it contains an entry written by "LogWrite Sample" (source). Double-click on
the entry. It will greet you with a "Hello World!" message.
In its simplest form, writing to an event log involves:
- Registering an event source (if not already registered):
if (!EventLog.SourceExists(source)) {
EventLog.CreateEventSource(source,log);
}
C#
|
- Creating a new instance of an EventLog component and setting its Source property:
EventLog aLog = new EventLog();
aLog.Source = source;
C#
|
- Calling the WriteEntry method:
String message = "some message";
aLog.WriteEntry(message, EventLogEntryType.Information);
C#
|
Now, you may want to try to modify the sample so it writes
error log entries instead of informational entries. Just change
the EventLogEntryType.Information to EventLogEntryType.Error, rebuild the
sample and run it again.
Example
VB LogWrite.exe
[This sample can be found at C:\DevFusion.Data\legacy\quickstart.developerfusion.co.uk\QuickStart\howto\samples\Services\EventLog\LogWrite\]
Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2004 Microsoft Corporation. All rights reserved.
|