Reputation: 49
I have a task to poll application event log periodically to check for new entries and process them, later parsing them to an .evtx file.
This task is not a problem. I am using a code like that:
using (var els = new EventLogSession())
{
string timeString = timestamp.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
string queryString = String.Format(
"<QueryList> <Query Id='0' Path='{0}'> <Select Path='{0}'> " +
"*[System[TimeCreated[@SystemTime>'{1}']]]</Select> </Query> </QueryList>",
logName, timeString);
var query = new EventLogQuery(logName, PathType.LogName, queryString) { Session = els };
var records = new List<EventRecord>();
using (var logReader = new EventLogReader(query))
{
EventRecord record;
while ((record = logReader.ReadEvent()) != null)
{
//log entries processed here
...
//finally export log messages to a file
els.ExportLogAndMessages(logName, PathType.LogName, queryString, fileName, true, CultureInfo.GetCultureInfo("en"));
}
}
}
Unfortunately I found out that after restarting my PC and starting application - EventLogReader always returns the same set of messages, even if I restart my application. That means - new messages do not appear in the results yielded by logReader.ReadEvent() method.
However - changing query string to a simple asterisk and passing it to EventLogQuery - resolves this situation, logReader returns all messages including new ones. For now, I stick with "*" query string and filter old entries with code, but this seems to be not the best solution to me.
Is it a mistake in my query? Is it a mistake with my handling of EventLogSession or EventLogReader objects? Is it a known MS bug?
Upvotes: 0
Views: 1391
Reputation: 1110
I know this is an old question, but it doesn't have an answer and I've been working in this area lately.
Possible issues with this code:
Use UTC time for your date, and
.ToString("o")
instead of
.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
Don't include any of the extraneous XML in the query string. You only need the query bit. So it should be:
string queryString = String.Format(
"*[System[TimeCreated[@SystemTime>'{0}']]]",
timeString);
Consider using an EventBookmark instead of constructing a complex query expression for date filtering. EventBookmarks were designed for that purpose. See How to create an EventBookmark when querying the event log for an example of using EventBookmark for a very similar kind of purpose.
Once you have an EventBookmark you simply use:
using (var logReader = new EventLogReader(query, EventBookmark))
to ensure that your reader starts at the entry after the previous bookmark.
Upvotes: 1