2012-09-12 123 views
8

我有以下代碼:EventLogQuery:如何形成查詢字符串?

string query = "???"; 

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

我試圖找出我需要查詢,以尋找與「SQLSERVERAGENT」來源的所有條目設置。

+2

如果我使用事件查看器設置過濾器,我可以看到它使用的原始XML查詢。我得到一個字符串,如''。這些工作(整個事情,減去XML標記,或只是提供者[@Name ='...']'? –

+0

會[C#:如何查詢具有給定事件ID的事件日誌細節? ](http://stackoverflow.com/questions/2462426/c-how-to-query-for-an-event-log-details-with-a-given-event-id)有幫助嗎? – Turbot

+0

我認爲[這篇文章是你的答案] [1] [1]:http://stackoverflow.com/a/8575390/284758 –

回答

1

我剛剛花了一個小時試圖爲自己解決類似問題,並認爲我會爲其他任何人以這種方式提供解決方案。評論應該相當自我解釋。

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 :) 
      } 
     }