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

时间:2012-09-12 01:47:25

标签: c# event-log

我有以下代码:

string query = "???";

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

我正在试图找出我需要设置查询的内容,以便查找源代码为“SQLSERVERAGENT”的所有条目。

1 个答案:

答案 0 :(得分: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 :) 
            }
        }