コード例 #1
0
        /// <summary>
        /// Validate the Windows event log section
        /// </summary>
        /// <param name="sourceSection"></param>
        /// <param name="id"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool ValidateSource(IConfigurationSection sourceSection, string id, IList <string> messages)
        {
            var logName = sourceSection["LogName"];

            var            eventLogQuery = new EventLogQuery(logName, PathType.LogName);
            EventLogReader reader        = null;

            try
            {
                reader = new EventLogReader(eventLogQuery, null);
                reader.ReadEvent();
                return(true);
            }
            catch (EventLogNotFoundException ex)
            {
                messages.Add(ex.Message);
                messages.Add($"Event Log Name: {logName} is not a valid log name in source ID: {id}!");
                return(false);
            }
            catch (Exception ex)
            {
                messages.Add(ex.ToString());
                messages.Add($"Unexpected exceptions. Event Log Name: {logName} in source ID: {id}.");
                return(false);
            }
            finally
            {
                reader?.Dispose();
            }
        }
コード例 #2
0
ファイル: EventLogSource.cs プロジェクト: tank0226/Tailviewer
        /// <inheritdoc />
        public void Dispose()
        {
            _cancellationTokenSource.Cancel();
            _scheduler.StopPeriodic(_readTask);

            _reader?.Dispose();
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: nla/event-transform
        public void Dispose()
        {
            eventReader.Dispose();

            if (outFileWriter != null)
            {
                logFileWriter.WriteLine("Closing output file");
                outFileWriter.Close();
                outFileWriter.Dispose();
            }

            if (logFileWriter != null)
            {
                logFileWriter.WriteLine("Closing log file");
                logFileWriter.Close();
                logFileWriter.Dispose();
            }

            // This object will be cleaned up by the Dispose method.
            // Therefore, you should call GC.SupressFinalize to
            // take this object off the finalization queue
            // and prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize(this);
        }
コード例 #4
0
 public void Dispose()
 {
     if (_reader != null)
     {
         _reader.Reset();
         _reader.Dispose();
         _reader = null;
     }
 }
コード例 #5
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _storage?.Dispose();
                }

                _eventLogReader?.Dispose();

                disposedValue = true;
            }
        }
コード例 #6
0
        /// <summary>
        /// Note this method is synchronous and must be called synchronously
        /// from NodeJS.
        /// </summary>
        /// <param name="input"></param>
        /// <returns>A delegate that must be called asynchronously from NodeJS</returns>
        public Task <object> GetActiveEventLogReader(dynamic input)
        {
            var logName      = input.logName;
            var reader       = new EventLogReader(logName, PathType.LogName);
            var readComplete = false;

            // The delegate returned is async
            return(Task.FromResult((object)(Func <object, Task <object> >)(async o =>
            {
                if (readComplete)
                {
                    return null;
                }

                return await Task <object> .Factory.StartNew(() =>
                {
                    var count = 0;
                    var events = new List <object>();
                    EventRecord evt;
                    while (count < BatchSize && null != (evt = reader.ReadEvent()))
                    {
                        count++;

                        events.Add(new
                        {
                            evt.Id,
                            evt.Version,
                            evt.Keywords,
                            evt.Qualifiers,
                            evt.LogName,
                            evt.MachineName,
                            evt.Level,
                            evt.TimeCreated,
                            evt.ProviderName,
                            evt.Task,
                            evt.Opcode,
                            User = evt.UserId?.Value,
                            evt.RecordId,
                            Properties = evt.Properties.Select(p =>
                            {
                                if (p.Value is byte[] a)
                                {
                                    return string.Join("", a.Select(element => element.ToString("X2")));
                                }

                                return p.Value.ToString();
                            })
                        });
                    }

                    if (count < 1)
                    {
                        readComplete = true;
                        reader.Dispose();
                        return null;
                    }

                    if (count < BatchSize)
                    {
                        readComplete = true;
                        reader.Dispose();
                    }

                    return events;
                });
コード例 #7
0
        public static void ReadAppLog()
        {
            //Начало лога - в самом низу. Оно самое старое
            //Конец лога - в самом верху. Он самый новый
            //Читаем самый первый лог
            //Берем его ID
            //Вычитаем тот, что храним
            //Получаем цифру смещения
            //Смещаемся
            //И читаем от него к концу (самому верху, самым новым)


            int SessionID = new Random().Next();

            if (Config.log.Work)
            {
                Log.Add("Session ID: " + SessionID + ". AppLog. Start reading");
            }

            string        LogName = "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational";
            EventLogQuery elQuery = new EventLogQuery(LogName, PathType.LogName);

            if (Config.log.Work)
            {
                Log.Add("Session ID: " + SessionID + ". AppLog. Query created");
            }

            EventLogReader elReader = new EventLogReader(elQuery);

            if (Config.log.Work)
            {
                Log.Add("Session ID: " + SessionID + ". AppLog. Reader created");
            }

            long SeekNumber = GetSeekNumber(elReader);

            if (Config.log.Work)
            {
                Log.Add("Session ID: " + SessionID + ". AppLog. Seek Number = " + SeekNumber);
            }


            elReader.Seek(System.IO.SeekOrigin.Current, SeekNumber);
            if (Config.log.Work)
            {
                Log.Add("Session ID: " + SessionID + ". AppLog. Seeked");
            }

            if (IgnoreLogs)//Если игнорируем старые логи - перейти читать в самый конец
            {
                if (Config.log.Work)
                {
                    Log.Add("Session ID: " + SessionID + ". AppLog. Ignore logs start");
                }

                elReader.Seek(System.IO.SeekOrigin.End, 0);

                if (Config.log.Work)
                {
                    Log.Add("Session ID: " + SessionID + ". AppLog. Ignore logs complete");
                }
            }


            if (Config.log.Work)
            {
                Log.Add("Session ID: " + SessionID + ". AppLog. Reading logs. Start");
            }
            for (EventRecord eventInstance = elReader.ReadEvent(); eventInstance != null; eventInstance = elReader.ReadEvent())
            {
                if (Config.NeedToStop)
                {
                    break;
                }

                long?    Index = eventInstance.RecordId;
                DateTime?time  = eventInstance.TimeCreated;

                if (Config.log.Work)
                {
                    Log.Add("Session ID: " + SessionID + ". AppLog. Index: " + Index + ". Time: " + time + ". ID: " + eventInstance.Id);
                }

                //Console.WriteLine(Index);
                if (Index <= Config.LastReadedAppLogIndex)
                {
                    if (Config.log.Work)
                    {
                        Log.Add("Session ID: " + SessionID + ". AppLog. Index: " + Index + ". Less or equal than Last Readed App Log Index: " + Config.LastReadedAppLogIndex + ". Go to next log");
                    }

                    continue;
                }

                if (eventInstance.Properties.Count < 3)
                {
                    if (Config.log.Work)
                    {
                        Log.Add("Session ID: " + SessionID + ". AppLog. Index: " + Index + ". eventInstance.Properties.Count < 3. Go to next log");
                    }

                    Config.LastReadedAppLogIndex = eventInstance.RecordId;
                    Config.Save();
                    continue;
                }

                if (eventInstance.Id == 21)
                {
                    ReadLog21(eventInstance);
                }
                else if (eventInstance.Id == 24)
                {
                    ReadLog24(eventInstance);
                }
                else if (eventInstance.Id == 25)
                {
                    ReadLog25(eventInstance);
                }

                Config.LastReadedAppLogIndex = eventInstance.RecordId;
                Config.Save();

                if (Config.log.Work)
                {
                    Log.Add("Session ID: " + SessionID + ". AppLog. Index: " + Index + ". Log read finish");
                }
            }

            elReader.Dispose();


            if (Config.log.Work)
            {
                Log.Add("Session ID: " + SessionID + ". AppLog. Finish reading");
            }
        }
コード例 #8
0
        static void Main(string[] args)
        {
            var dirInfo  = new DirectoryInfo(virtualPath);
            var fileList = dirInfo.GetFiles();

            FileStream   outputStream = null;
            StreamWriter outputWriter = null;

            try
            {
                outputStream = new FileStream("Events.xml", FileMode.Create, FileAccess.ReadWrite);
                outputWriter = new StreamWriter(outputStream);
                outputWriter.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                outputWriter.WriteLine("<Logs>");

                foreach (var logFile in fileList)
                {
                    EventLogQuery  logQuery   = null;
                    EventLogReader logReader  = null;
                    EventRecord    logRecord  = null;
                    List <string>  xmlRecords = null;

                    try
                    {
                        logQuery   = new EventLogQuery(string.Format("{0}{1}", actualPath, logFile.Name), PathType.FilePath, queryString);
                        logReader  = new EventLogReader(logQuery);
                        xmlRecords = new List <string>();

                        while ((logRecord = logReader.ReadEvent()) != null)
                        {
                            xmlRecords.Add(logRecord.ToXml());
                        }
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        Console.ForegroundColor = ConsoleColor.DarkRed;
                        Console.Write(ex.GetType());
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(": {1}", ex.GetType(), ex.Message);

                        Console.WriteLine();
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.WriteLine("This program requires administrative rights in order to function.", ex.Message);
                        Console.WriteLine("Please right click on the executable and select Run as Administrator.", ex.Message);
                        Console.ForegroundColor = ConsoleColor.Gray;

                        break;
                    }
                    catch (EventLogException ex)
                    {
                        Console.ForegroundColor = ConsoleColor.DarkRed;
                        Console.Write(ex.GetType());
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(": {1}", ex.GetType(), ex.Message);
                        Console.ForegroundColor = ConsoleColor.Gray;
                    }
                    finally
                    {
                        if (logRecord != null)
                        {
                            logRecord.Dispose();
                            logRecord = null;
                        }

                        if (logReader != null)
                        {
                            logReader.Dispose();
                            logReader = null;
                        }

                        if (xmlRecords.Any())
                        {
                            outputWriter.WriteLine("\t<EventLog LogName=\"{0}\">", logFile.Name.Replace(logFile.Extension, string.Empty).Replace("%4", "/"));
                            xmlRecords.ForEach(i =>
                            {
                                outputWriter.WriteLine("\t\t{0}", i);
                                outputWriter.Flush();
                            });

                            outputWriter.WriteLine("\t</EventLog>");
                            outputWriter.Flush();
                        }

                        xmlRecords.Clear();
                        xmlRecords = null;
                    }
                }

                outputWriter.WriteLine("</Logs>");
                outputWriter.Flush();
            }
            finally
            {
                if (outputStream != null)
                {
                    outputStream.Flush();
                    outputStream.Close();

                    outputStream.Dispose();
                    outputStream = null;
                }
            }

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("This program has created a file called Events.xml, located within the same folder you ran this program from.");
            Console.WriteLine("You'll need to send me the xml file.");
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.Write("Press any key to exit.");
            Console.Read();
        }
コード例 #9
0
        }  //ETWTraceInBackground_Start_APPS()

        private void ETWTraceInBackground_DoWork_APPS(object sender, DoWorkEventArgs e)
        {
            // This is the background thread
            int              count    = 0;
            string           etwclass = e.Argument as string;
            BackgroundWorker worker   = sender as BackgroundWorker;

            Thread.CurrentThread.Name = "ETWReaderAPPS";
            //Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;

            try
            {
                string         sQuery                 = "*[System/Level>0]";
                EventLogQuery  Q_Operational          = new EventLogQuery(etwclass, PathType.LogName, sQuery);
                EventBookmark  Ev_OperationalBookmark = null;
                EventLogReader R_Operational;
                R_Operational = new EventLogReader(Q_Operational); // Walk through existing list to create a bookmark
                R_Operational.Seek(System.IO.SeekOrigin.End, 0);
                for (EventRecord eventInstance = R_Operational.ReadEvent();
                     null != eventInstance;
                     eventInstance = R_Operational.ReadEvent())
                {
                    Ev_OperationalBookmark = eventInstance.Bookmark;
                }
                R_Operational.Dispose();
                WaitingForEventStart_APPS = false;

                worker.ReportProgress(count++);

                while (!worker.CancellationPending && !PleaseStopCollecting)
                {
                    Thread.Sleep(1000);
                    R_Operational = new EventLogReader(Q_Operational, Ev_OperationalBookmark);
                    for (EventRecord eventInstance = R_Operational.ReadEvent();
                         null != eventInstance;
                         eventInstance = R_Operational.ReadEvent())
                    {
                        Ev_OperationalBookmark = eventInstance.Bookmark;
                        try
                        {
                            DateTime  et    = eventInstance.TimeCreated.GetValueOrDefault();
                            EventItem eItem = new EventItem((int)et.Ticks, et.Ticks, et.Ticks, et, eventInstance.ProcessId.ToString(), (int)eventInstance.ProcessId, (int)eventInstance.ThreadId,
                                                            eventInstance.LogName, "Application", eventInstance.Id.ToString(), eventInstance.LevelDisplayName, eventInstance.FormatDescription(), "");
                            worker.ReportProgress(count++, eItem);
                        }
                        catch
                        {
                            // app provider might be virtual or missing
                            string leveldisplayname = "";
                            string stuff            = "Formatter not available. Details:";
                            int    ProcessId        = -1;
                            int    ThreadId         = -1;
                            switch (eventInstance.Level)
                            {
                            case 1:
                                leveldisplayname = "Critical";
                                break;

                            case 2:
                                leveldisplayname = "Error";
                                break;

                            case 3:
                                leveldisplayname = "Warning";
                                break;

                            case 4:
                                leveldisplayname = "Information";
                                break;

                            default:
                                break;
                            }
                            foreach (EventProperty p in eventInstance.Properties)
                            {
                                stuff += p.Value.ToString() + "  ";
                            }
                            if (eventInstance.ProcessId != null)
                            {
                                ProcessId = (int)eventInstance.ProcessId;
                            }
                            if (eventInstance.ThreadId != null)
                            {
                                ThreadId = (int)eventInstance.ThreadId;
                            }
                            DateTime  et    = eventInstance.TimeCreated.GetValueOrDefault();
                            EventItem eItem = new EventItem((int)et.Ticks, et.Ticks, et.Ticks, et, eventInstance.ProcessId.ToString(), (int)eventInstance.ProcessId, (int)eventInstance.ThreadId,
                                                            eventInstance.LogName, "Application", eventInstance.Id.ToString(), leveldisplayname, stuff, "");
                            worker.ReportProgress(count++, eItem);
                        }
                    }
                    R_Operational.Dispose();
                }
            }
            catch
            {
                WaitingForEventStart_APPS = false;
            }
        } // ETWTraceInBackground_DoWork_APPS()
コード例 #10
0
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     log.CancelReading();
     log.Dispose();
     log = null;
 }