2012-09-12 124 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 :) 
      } 
     }