Search code examples
c#event-log

EventLogQuery ignoring TimeCreated criteria


I am using the following helper function:

public List<EventRecord> GetEvents(DateTime afterTime)
{
    var formattedDateTime = $"{afterTime:yyyy-MM-dd}T{afterTime:HH:mm:ss}.000000000Z";

    var query     = $"*[(System/Provider/@Name='.Net Runtime') and (System/EventID=1000) and (System/TimeCreated/@SystemTime >= '{formattedDateTime}')]";

    var queryResult = new EventLogQuery("Application", PathType.LogName, query);
    var reader      = new EventLogReader(queryResult);
    
    var events = new List<EventRecord>();
    while (true)
    {
        var rec = reader.ReadEvent();

        if (rec == null)
        {
            break;
        }

        events.Add(rec);
    }

    return events;
}

This code almost works except the query seems to be ignoring the TimeCreated entirely. It's returning all events with the given ProviderName and EventId. I have tried all sorts of different things to get this to work but no matter what, TimeCreated is ignored.

Anyone see what I'm doing wrong?

Edit 1

Even replacing the query line with:

var query     = $"*[System[TimeCreated[@SystemTime >= '{formattedDateTime}']]]";

Doesn't work. Returns all events regardless of when they were Created.

Edit 2

So I tried using the 'custom view' builder to generate an XML query for me and what I found was even more perplexing:

So currently the time displayed on my machine is: 2:42pm. In 24 hour time it should be 14:42pm.

When I create a query using the custom view and select: From: 'Events On' 03/18/2021 2:42pm , it creates the following:

<QueryList>
  <Query Id="0" Path="Application">
    <Select Path="Application">*[System[Provider[@Name='.NET Runtime'] and (EventID=1000) and TimeCreated[@SystemTime&gt;='2021-03-18T20:42:13.000Z']]] </Select>
  </Query>
</QueryList>

Why on gods green earth did it convert 2:42pm to 20:42?


Solution

  • So apparently you need to convert your time to UniversalTime for this to work.

    Here is a working sample:

    public List<EventRecord> GetEvents(DateTime afterTime)
    {
        var formattedDateTime = afterTime.ToUniversalTime().ToString("o");
    
        var query     = $"*[System[Provider[@Name='.NET Runtime'] and (EventID=1000) and TimeCreated[@SystemTime>='{formattedDateTime}']]]";
    
        var queryResult = new EventLogQuery("Application", PathType.LogName, query);
        var reader      = new EventLogReader(queryResult);
        
        var events = new List<EventRecord>();
        while (true)
        {
            var rec = reader.ReadEvent();
    
            if (rec == null)
            {
                break;
            }
    
            events.Add(rec);
        }
    
        return events;
    }