EventLogQuery:如何形成查询字符串? [英] EventLogQuery: How to form query string?

查看:171
本文介绍了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"源的所有条目.

I'm trying to figure out what I need to set query to in order to look for all entries with a source of "SQLSERVERAGENT".

推荐答案

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

I have just spent an hour trying to solve similar for myself and thought I would contribute back with the solution for anyone else that comes this way. The comments should be fairly self explanatory.

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();
        }
    }
}

这篇关于EventLogQuery:如何形成查询字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆