【问题标题】:EventLogQuery: How to form query string?EventLogQuery:如何形成查询字符串?
【发布时间】:2012-09-12 01:47:25
【问题描述】:

我有以下代码:

string query = "???";

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

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

【问题讨论】:

  • 如果我使用事件查看器设置过滤器,我可以看到它使用的原始 XML 查询。我得到一个像<Select Path="Application">*[System[Provider[@Name='SourceName']]]</Select> 这样的字符串。是否有任何工作(整个事情,减去 XML 标记,或只是 Provider[@Name='...']
  • 我认为[这篇文章是你的答案][1]。 [1]:stackoverflow.com/a/8575390/284758
  • 谢谢,我实际上在发布此问题后也发现了这个问题,它需要是:*[System/Provider/@Name=\"SQLSERVERAGENT\"
  • 但是,我现在对如何阅读消息感到困惑。有各种属性,包含有关事件的各种信息......但没有我能看到的实际消息字符串的属性???

标签: c# event-log


【解决方案1】:

我刚刚花了一个小时试图为自己解决类似问题,并认为我会为其他任何人提供解决方案。 cmets 应该是相当不言自明的。

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

【讨论】:

  • 简而言之,使用 XPath 语法。
  • 这缺少一大堆Dispose() 电话
  • 感谢@Liam,随时使用模组进行编辑。我回答的目的是为一个相当琐碎的问题提供最简单的代码,但是是的,需要使用或处置。这是不久前的事了,可能还有更好的选择可供探索。
猜你喜欢
  • 2014-01-15
  • 2011-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
  • 2016-03-06
相关资源
最近更新 更多