Monday, January 2, 2012

How to Read/Write Windows Event Logs?


Windows provides central logging mechanism to write/read logs. Windows provides three most popular event logs,

  • Application
  • System
  • Security
Application related events are logged under application log similarly System and Security related events logged under system and security logs respectively. 
Below image displays Windows logs.


Event Log


EventLog class provides interaction with windows event logs. Using EventLog we can read from existing log and write entries to log. We can also create new custom event source other than system defined event source.


void EventLogDemo_Loaded(object sender, RoutedEventArgs e)
{
    EventLog.WriteEntry("Application", "Your application loaded successfully...");
}

The above line of code makes log entry in Application Log defined in Windows Logs with custom message.




We can also create our own custom log and write event logs on newly defined log.


void EventLogDemo_Loaded(object sender, RoutedEventArgs e)
{
    if (!EventLog.SourceExists("TempLog"))
    {
        EventLog.CreateEventSource("TempLog", "Application");
        Console.WriteLine("Event log created sucessfully");
    }
    EventLog.WriteEntry("TempLog", "Your application loaded successfully...");
}

As per above image, Application log displays one log created in Application log and displays custom message. EventLog.CreateEventSource method creates event source. This method requires Administrative rights to execute.  Once event source is created we can add new event log on it.

Reading Event Log


We can read event log list using EventLog class. EventLog class provides GetEventLogs method which returns collection of EventLogEntry. This method retrieves all entries from given log. See below code,


void EventLogDemo_Loaded(object sender, RoutedEventArgs e)
{
    EventLog appLog = new EventLog("Application");

    foreach (EventLogEntry entry in appLog.Entries)
        Console.WriteLine("Index: {0}, Source: {1}, EntryType: {2}, Time: {3}, Message: {4}",
            entry.Index, entry.Source, entry.EntryType, entry.TimeWritten, entry.Message);
}


Above code retrieves all log information from Application log. Similarly we can read all the items from System, Security and other custom logs. The above code will take some time to execute because it will retrieve all the items available in Application log. Below code retrieve single log item from Application event log.


EventLog appLog = new EventLog("Application");
EventLogEntry lastEntry = appLog.Entries[appLog.Entries.Count - 1];
Console.WriteLine("Index: {0}, Source: {1}, EntryType: {2}, Time: {3}, Message: {4}",
        lastEntry.Index, lastEntry.Source, lastEntry.EntryType, lastEntry.TimeWritten, lastEntry.Message);



No comments:

Post a Comment