Search this blog

Wednesday, August 19, 2009

Filter the EventLog Entries thru C# Code

To Read & Write Event Log thru C#, System.Diagnostics.EventLog class will help. When we read from Eventlog, the following code will helps

EventLog EvLog = new EventLog("Application", ".");
foreach (System.Diagnostics.EventLogEntry entry in EvLog.Entries)
{
.....
}

This code will read all the Entries from Event Log, here there is no option to filter the entries of Event log.To implement the filter on the Eventlog, we have to check the value one by one in the for each loop, as given below

foreach (System.Diagnostics.EventLogEntry entry in EvLog.Entries)
{
if (entry.TimeWritten > DateTime.Now.AddDays(-1))
{
.....
}
}

If the list of entries are more in the Event log, then this is not proper way. It will leads to performance issue.To avoid this, we can use WMI Query Language. this Query Language is same as SQL Query structure, we can filter the data in the same way of SQL.

Win32_NTLogEvent is a WMI class which is used to translate instances from the Windowsevent log.

Have a look at the following sample code, (written in C# and windows application)

string SomeDateTime = "20090817000000.000000+000";
string Query = String.Format("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Application' AND TimeGenerated > '{0}'", SomeDateTime);

ManagementObjectSearcher mos = new ManagementObjectSearcher(Query);
object o;
foreach (ManagementObject mo in mos.Get())
{
foreach (PropertyData pd in mo.Properties)
{
o = mo[pd.Name];
if (o != null)
{
listBox1.Items.Add(String.Format("{0}: {1}", pd.Name,mo[pd.Name].ToString()));
}
}
listBox1.Items.Add("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
}

In this sample code, we are using following Query

SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Application' AND TimeGenerated > 20090817000000.000000+000

This query will fetch the data from Application Log, where the log created on or after 17-Aug-2008This is code display the filtered output in listbox control as shown below

1 comment: