Wednesday, June 17, 2009

Reading and Writing Event Log

In my computer, right click manage, we can see the events logs by event viewer. The majory types of the event log are: system, security and application types.

In order an application program writing events to the Event log, the application need to be register as an Evnet Source. We can use Regedit.exe to register manually: locate the registry subkey: HKEY_LOCAL_MACHINE\SYSTEM|CurrentControlSet\Services\Eventlog\Application, right click the Application subkey, and click New and type the event source name.

We can also use EventLog object to register event source, read and write to event logs. Reference the name space, System.Diagnostics, the code can be like:

1. Register Application EventLog Source:

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

or:

if(!EventLog.Exists("My Log"))
EventLog.CreateEventSource("My App","My Log");

2. Log Events
We can use EventLog.WriteEntry() method and specify the message, type, eventID,category, rawData. The code sample like:

EventLog myLog=new EventLog("Application");
//Notice this parameter can also be "System",
//"Security", so we can also read/write
//systme and security logs.
myLog.Source="My Application";
myLog.WriteEntry("Could not connect",EventLogEntryType.Error, 1001,1);

3. Read Events
We can also create EventLog instance and access the EventLog.Entries Collection:
EventLog myLog=new EventLog("Application");
foreach(EventLogEntry entry in myLog.Entries)
Console.WriteLine(entry.Message);

No comments: