EventLogQuery:如何形成查询字符串?

我有以下代码:

string query = "???"; EventLogQuery elq = new EventLogQuery("Application", PathType.LogName, query); elq.Session = new EventLogSession("xxxx"); EventLogReader elr = new EventLogReader(elq); 

我正在试图弄清楚我需要设置查询以查找源为“SQLSERVERAGENT”的所有条目。

我花了一个小时试图为自己解决类似问题,并认为我会为这样的其他任何人提供解决方案。 评论应该是相当自我解释的。

  public void ReadSqlAgentEventMessages() { // Force culture to en-US if required, some people get a null from FormatDescription() and this appently solves it. // My culture is set as en-GB and I did not have the issue, so I have left it as a comment to possibly ease someone's pain! // Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); EventLogQuery eventlogQuery = new EventLogQuery("Application", PathType.LogName, "*[System/Provider/@Name=\"SQLSERVERAGENT\"]"); EventLogReader eventlogReader = new EventLogReader(eventlogQuery); // Loop through the events returned for (EventRecord eventRecord = eventlogReader.ReadEvent(); null != eventRecord; eventRecord = eventlogReader.ReadEvent()) { // Get the description from the eventrecord. string message = eventRecord.FormatDescription(); // Do something cool with it :) } }