Search code examples
c#asp.netlinqevent-viewer

Remote Event Logs Paging


I have the following requirement

  • Read a remote machines event logs
  • Pass over credentials
  • Allow a user to page through this in an MVC Application

From my research I believe this can be achieved using the EventLogSession combined with the EventLogQuery & EventLogReader.

Whilst I've managed to successfully conenct to a remote machine with credentials and read the log files I'm stuck with the paging aspect. I don't know how to do the equivalent of LINQ's Skip & Take methods with the EventLogQuery.

Some of these machines will have > 20 000 logs and I'd like to avoid loading them all into memory before paging.

Is there a way I can achieve paging with the EventLogQuery?


Solution

  • Here's an idea of how to approach this using the lazy evaluation capabilities of yield return. Given a query to execute using EventLogQuery, you can do as follows:

    public IEnumerable<EventRecord> QueryEventRecords(string queryString)
    {
        var query = new EventLogQuery("Application", PathType.LogName, queryString);
        using (var reader = new EventLogReader(query))
        {
            EventRecord eventRecord;
            while ((eventRecord = reader.ReadEvent()) != null)
            {
                yield return eventRecord;
            }
        }
    }
    

    Which you can then execute the query and then use your favourite LINQ operators on the IEnumerable.

    var result = QueryEventRecords("*[System[(Level = 3)]]")
        .Skip(10)
        .Take(10)
        .ToList();
    

    That said, paging a remote PC isn't going to fly in an MVC application - retaining statefulness of the iterator between screen paging would not be advisable. What might better would be to pre-fetch all events in the query of interest from the remote machines and instead save these to a central database (i.e. similar to enterprise software like SCOM). You can then browse through the event data at your leisure using an ORM like EF.