public class EventScanner
{
private DateTime _cutoffDate = DateTime.MinValue;
// CreateCutoff( hours ) : this function substracts the number of hours from the current
// time to create a time window for reported log entries
private void CreateCutoff( double hours )
{
_cutoffDate = DateTime.Now.AddHours( hours * -1);
Console.WriteLine( "Event Log Snapshot from {0} {1} through {2} {3}", _cutoffDate.ToShortDateString(), _cutoffDate.ToShortTimeString(), DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString());
}
// CreateEventLogReader( logName, machineName ) : This function creates an eventlog
// object for the associated log name and machine name (if passed).
public EventLog CreateEventLogReader( string logName, string machineName )
{
EventLog log = null;
if( machineName.Length > 0 )
log = new EventLog(logName, machineName );
else
log = new EventLog(logName);
return log;
}
// WriteEventLog() : This function takes the log name and attaches to it
public void WriteEventLog(string logName, string machineName, double hours)
{
// first, we'll open the log
using( EventLog log = CreateEventLogReader( logName, machineName ))
{
// next we'll create our timespan of interest (hours subtracted from current time)
CreateCutoff(hours);
// finally, we'll scan the log for entries we're looking for.
// NOTE: here is where you can change the entry type based on what you are seeking
foreach( EventLogEntry entry in log.Entries )
{
if( entry.TimeWritten >= _cutoffDate && entry.EntryType == EventLogEntryType.Error)
Console.WriteLine( string.Format("{0},{1} {2},{3}", entry.Source, entry.TimeWritten.ToShortDateString(), entry.TimeWritten.ToShortTimeString(), FormatMessage(entry.Message) ));
entry.Dispose();
}
}
}
// the following string fragment appears on each log entry - apparently due to a
// translation dll not being loaded.
private const string _messageFormatIndicator = "following replacement strings:";
private string FormatMessage(string entry)
{
string newEntry = entry;
// make certain the generic handler error is ignored
int truncPosition = entry.IndexOf( _messageFormatIndicator ) ;
if( truncPosition >= 0 )
{
truncPosition += _messageFormatIndicator.Length;
newEntry = entry.Substring( truncPosition, entry.Length - truncPosition );
}
// get rid of CR/LF combinations for easier reading
newEntry = newEntry.Replace("\n", "{LF}");
newEntry = newEntry.Replace("\r", "{CR}");
// get rid of embedded commas to prevent CSV parsing problems
newEntry = newEntry.Replace(",", "_");
return newEntry;
}
}