获取崩溃程序的事件日志的可能性

Possibility to get the eventlog of a crashed program

我正在编写一个监控程序的工具。如果我正在监视的程序崩溃了,我想得到 windows 事件日志错误,为什么它崩溃了。

目前我尝试获取最后 2 秒的所有事件日志,因为我的程序没有响应。但是当我尝试添加 Timespan 时,过滤给了我一个错误。没有时间跨度它确实有效

错误:System.Diagnostics.Eventing.Reader.EventLogException 指定的查询无效。

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) {

                    }
                    
                }
            }

一个简单的方法是计算开始和结束时间并将它们用于查询:

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

            }
        }