Search code examples
c#event-log

Possibility to get the eventlog of a crashed program


I am programming a tool for monitoring programs. If a Programs which I am monitoring crashed I want to get the windows Eventlog Error why it crashed.

At the moment I try to get all eventlogs of the last 2 seconds since my program doesn't response. But the filtering gives me an errrr when I try to add a Timespan. Whithout timespan it does work

Error: System.Diagnostics.Eventing.Reader.EventLogException The specified query is invalid.

DateTime now = DateTime.Now;
            DateTime secondsearlier = now.AddSeconds(-2);
            TimeSpan ts =  now-secondsearlier;


            Console.WriteLine("yuhu");
            EventLogSession session;
            session = new EventLogSession();
            string filter = $"Select*[System[(Level = 1  or Level = 2) and TimeCreated[timediff(@SystemTime) & lt;= 3600000]]]";
            string fidlter = $"*[System[(Level=1  or Level=2)]]";
            
          
            var query = new EventLogQuery("Application", PathType.LogName, filter);
            var reader = new EventLogReader(query);

            EventRecord record;
          //  Console.WriteLine(reader.ReadEvent().ToString());
            
            while ((record = reader.ReadEvent()) != null) {
                using (record) {
                    try {
                        Console.WriteLine("{0} {1}: {2}", record.TimeCreated, record.LevelDisplayName, record.FormatDescription());
                    }
                    catch(Exception e) {

                    }
                    
                }
            }

Solution

  • A simple approach would be to calculate the start and end time and use those for the query:

            var startTime = DateTime.Now.AddMinutes(-120);//Set here the time range you want to select
            var endTime = DateTime.Now;
    
            var query = $"*[System[(Level=1 or Level=2)]] and *[System[TimeCreated[@SystemTime >= '{startTime.ToUniversalTime():O}']]] and *[System[TimeCreated[@SystemTime <= '{endTime.ToUniversalTime():O}']]]";
    
            var elq = new EventLogQuery("Application", PathType.LogName, query);
            var reader = new EventLogReader(elq);
    
            EventRecord record;            
            while ((record = reader.ReadEvent()) != null)
            {
                using (record)
                {
                    try
                    {
                        Console.WriteLine("{0} {1}: {2}", record.TimeCreated, record.LevelDisplayName, record.FormatDescription());
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: {0}", e.Message);
                    }
    
                }
            }