那么我提出的解决方案确实使用System.Diagnostics.EventLog并简单地迭代所有事件以过滤我想要的事件。我想这很简单,我只是认为会有一个更有效的界面。非常欢迎任何建议或改进!
我创建了一种方法来返回某个时间以来的事件日志条目:
/// <summary>
/// Steps through each of the entries in the specified event log and returns any that were written
/// after the given point in time.
/// </summary>
/// <param name="logName">The event log to inspect, eg "Application"</param>
/// <param name="writtenSince">The point in time to return entries from</param>
/// <param name="type">The type of entry to return, or null for all entry types</param>
/// <returns>A list of all entries of interest, which may be empty if there were none in the event log.</returns>
public List<EventLogEntry> GetEventLogEntriesSince(string logName, DateTime writtenSince, EventLogEntryType type)
{
List<EventLogEntry> results = new List<EventLogEntry>();
EventLog eventLog = new System.Diagnostics.EventLog(logName);
foreach (EventLogEntry entry in eventLog.Entries)
{
if (entry.TimeWritten > writtenSince && (type==null || entry.EntryType == type))
results.Add(entry);
}
return results;
}
在我的测试类中,我存储了一个时间戳:
private DateTime whenLastEventLogEntryWritten;
在测试设置期间,我将时间戳设置为写入最后一个事件日志条目的时间:
EventLog eventLog = new EventLog("Application");
whenLastEventLogEntryWritten = eventLog.Entries.Count > 0 ?
eventLog.Entries[eventLog.Entries.Count - 1] : DateTime.Now;
在我的测试结束时,我检查没有事件日志错误:
Assert.IsEmpty(GetEventLogEntriesSince("Application",
whenLastEventLogEntryWritten,
EventLogEntryType.Error),
"Application Event Log errors occurred during test execution.");