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

Bra*_*ore 8 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);
Run Code Online (Sandbox Code Playgroud)

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

Mur*_*oft 5

我刚刚花了一个小时尝试为自己解决类似的问题,并认为我会为其他遇到这种情况的人提供解决方案。这些评论应该是相当不言自明的。

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\"]");
    using (EventLogReader eventlogReader = new EventLogReader(eventlogQuery))
    {
        EventRecord eventRecord = eventlogReader.ReadEvent();
        try
        {

            // Loop through the events returned
            for (null != eventRecord; eventRecord = eventlogReader.ReadEvent())
            {
                // Get the description from the eventrecord. 
                string message = eventRecord.FormatDescription();

                // Do something cool with it :) 
            }
        }
        finally
        {
            if (eventRecord != null)
                eventRecord.Dispose();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 简而言之,使用 XPath 语法。 (2认同)
  • 这缺少一大堆 `Dispose()` 调用 (2认同)