9

我有以下代码:

string query = "???";

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

我试图弄清楚我需要将查询设置为什么,以便查找具有“SQLSERVERAGENT”源的所有条目。

4

1 回答 1

3

我刚刚花了一个小时试图为自己解决类似的问题,并认为我会为其他任何以这种方式出现的人提供解决方案。评论应该是不言自明的。

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();
        }
    }
}
于 2016-11-14T15:42:57.173 回答