public void Seek() { using (var eventLog = new EventLogReader("Application")) { using (EventRecord record = eventLog.ReadEvent()) { eventLog.Seek(record.Bookmark); eventLog.Seek(IO.SeekOrigin.Begin, 0); eventLog.Seek(IO.SeekOrigin.Current, 0); eventLog.Seek(IO.SeekOrigin.End, 0); } } }
private static void TestEventRead() { string LogName = "Application", SearchString = null, XPathQuery = null; int MaxEvents = 100; bool SearchUseRegExp = false; using (EventLogSession eventLogSession = new EventLogSession()) { EventLogQuery eventLogQuery = string.IsNullOrWhiteSpace(XPathQuery) ? new EventLogQuery(LogName, PathType.LogName) { Session = eventLogSession, TolerateQueryErrors = true, ReverseDirection = true } : new EventLogQuery(LogName, PathType.LogName, XPathQuery) { Session = eventLogSession, TolerateQueryErrors = true, ReverseDirection = true }; int eventReadCounter = MaxEvents; using (EventLogReader eventLogReader = new EventLogReader(eventLogQuery)) { eventLogReader.Seek(System.IO.SeekOrigin.Begin, 0); do { if (eventReadCounter <= 0) { break; } EventRecord eventData = eventLogReader.ReadEvent(); if (eventData == null) { break; } if (string.IsNullOrWhiteSpace(SearchString)) { Console.WriteLine($"{eventData.TimeCreated}: {eventData.FormatDescription()}, {eventData.KeywordsDisplayNames}"); eventReadCounter--; } else { if (Regex.IsMatch(eventData.FormatDescription(), SearchUseRegExp ? SearchString : Regex.Escape(SearchString), RegexOptions.IgnoreCase)) { Console.WriteLine($"{eventData.TimeCreated}: {eventData.FormatDescription()}"); eventReadCounter--; } } eventData.Dispose(); } while (true); } return; } }
static void ParseEventsParallel() { var sw = Stopwatch.StartNew(); var query = new EventLogQuery("Application", PathType.LogName, "*"); const int BatchSize = 100; ConcurrentQueue <EventRecord> events = new ConcurrentQueue <EventRecord>(); var readerTask = Task.Factory.StartNew(() => { using (EventLogReader reader = new EventLogReader(query)) { EventRecord ev; bool bFirst = true; int count = 0; while ((ev = reader.ReadEvent()) != null) { if (count % BatchSize == 0) { events.Enqueue(ev); } count++; } } myHasStoppedReading = true; }); ConcurrentQueue <KeyValuePair <string, EventRecord> > eventsWithStrings = new ConcurrentQueue <KeyValuePair <string, EventRecord> >(); Action conversion = () => { EventRecord ev = null; using (var reader = new EventLogReader(query)) { while (!myHasStoppedReading || events.TryDequeue(out ev)) { if (ev != null) { reader.Seek(ev.Bookmark); for (int i = 0; i < BatchSize; i++) { ev = reader.ReadEvent(); if (ev == null) { break; } eventsWithStrings.Enqueue(new KeyValuePair <string, EventRecord>(ev.FormatDescription(), ev)); } } } } }; Parallel.Invoke(Enumerable.Repeat(conversion, 8).ToArray()); sw.Stop(); Console.WriteLine($"Got {eventsWithStrings.Count} events with strings in {sw.Elapsed.TotalMilliseconds:N3}ms"); }
static long GetSeekNumber(EventLogReader elReader) { EventRecord eventInstance = elReader.ReadEvent(); elReader.Seek(System.IO.SeekOrigin.Current, -1); long?Seek = Config.LastReadedAppLogIndex - eventInstance.RecordId + 1; return((long)Seek); }
public static long?FetchLatestEventId(String computerName, String domain, String username, String password) { SecureString securePassword = ToSecureString(password); EventLogQuery query = new EventLogQuery("Security", PathType.LogName, "*[System]"); query.Session = new EventLogSession(computerName, domain, username, securePassword, SessionAuthentication.Default); EventLogReader logReader = new EventLogReader(query); logReader.Seek(SeekOrigin.End, 0); EventRecord latestEvent = logReader.ReadEvent(); return(latestEvent != null ? latestEvent.RecordId : 0); }
private void ProcessReader(EventLogReader reader, EventLogReaderDelegate _delegate) { EventRecord record; while ((record = reader.ReadEvent()) != null) { using (record) { _delegate(record); } } reader.Seek(new SeekOrigin(), 0); //Taylor Swift - Begin Again :D }
public override void Execute(object parameter) { using (EventLogReader EventLogReader = new EventLogReader(EventLogQuery) { BatchSize = Pagination }) { if (EventBookmark is object) { EventLogReader.Seek(EventBookmark, 1); } ICollection <EventRecord> Enumeration = new Collection <EventRecord>(); for (int i = Pagination; i > 0 && EventLogReader.ReadEvent() is EventRecord EventRecord; i--) { Enumeration.Add(EventRecord); EventBookmark = EventRecord.Bookmark; } Action.Invoke(Enumeration); }; }
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"); } }
} //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()
/// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> /// <exception cref="T:System.InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> public void Reset() { log.Seek(System.IO.SeekOrigin.Begin, 0L); }
private async Task ReaderRoutine() { var delay = MinReaderDelayMs; EventRecord entry = null; EventBookmark eventBookmark = null; using (var eventLogReader = new EventLogReader(new EventLogQuery(_logName, PathType.LogName, _query))) { if (eventBookmark == null) { eventLogReader.Seek(SeekOrigin.Begin, 0); // now, for some odd reason, Seek to End will set the reader BEFORE the last record, // so we do a random read here var last = DoRead(eventLogReader); eventBookmark = last?.Bookmark; last?.Dispose(); } } await Task.Yield(); _logger?.LogInformation("{0} Id {1} started reading", nameof(WindowsEventPollingSource), Id); while (!_cts.Token.IsCancellationRequested) { int batchCount = 0; try { // setting batch size is pretty important for performance, as the .NET wrapper will attempt to query events in batches // see https://referencesource.microsoft.com/#system.core/System/Diagnostics/Eventing/Reader/EventLogReader.cs,149 using (var eventLogReader = new EventLogReader(new EventLogQuery(_logName, PathType.LogName, _query), eventBookmark) { BatchSize = 128 }) { while ((entry = DoRead(eventLogReader)) != null) { batchCount++; #if DEBUG Interlocked.Increment(ref _total); #endif eventBookmark = entry.Bookmark; this.LastEventLatency = DateTime.Now.Subtract(entry.TimeCreated ?? DateTime.Now); OnEventRecord(entry); if (batchCount == BatchSize) { this._logger?.LogDebug($"Read max possible number of events: {BatchSize}"); break; } _cts.Token.ThrowIfCancellationRequested(); } if (entry is null) { _logger?.LogDebug("Read {0} events", batchCount); } } delay = GetNextReaderDelayMs(delay, batchCount, this._logger); batchCount = 0; _logger?.LogDebug("Delaying {0}ms", delay); await Task.Delay(delay, _cts.Token); } catch (OperationCanceledException ex) { _logger?.LogWarning(0, ex, "Error reading events, operation was canceled."); break; } catch (Exception ex) { _logger?.LogError(0, ex, "Error reading events"); } } _logger?.LogInformation("{0} Id {1} stopped reading", nameof(WindowsEventPollingSource), Id); }
protected override EventListDataItem[] GetOutputData(DataItemBase[] inputDataItems) { try { using (EventLogSession eventLogSession = new EventLogSession()) { EventLogQuery eventLogQuery = string.IsNullOrWhiteSpace(XPathQuery) ? new EventLogQuery(LogName, PathType.LogName) { Session = eventLogSession, TolerateQueryErrors = true, ReverseDirection = true } : new EventLogQuery(LogName, PathType.LogName, XPathQuery) { Session = eventLogSession, TolerateQueryErrors = true, ReverseDirection = true }; int returnedEventsCounter = MaxEvents; int searchedEventsCounter = MaxSearchEvents; List <EventInfo> eventList = new List <EventInfo>(MaxEvents); using (EventLogReader eventLogReader = new EventLogReader(eventLogQuery)) { eventLogReader.Seek(System.IO.SeekOrigin.Begin, 0); // from latest event to the past. ReverseDirection swaps End and Begin for seek method do { if (returnedEventsCounter <= 0 || searchedEventsCounter <= 0) { break; } EventRecord eventData = eventLogReader.ReadEvent(); searchedEventsCounter--; if (eventData == null) { break; } if (string.IsNullOrWhiteSpace(SearchString)) { eventList.Add(CreateEventInfo(eventData)); returnedEventsCounter--; } else { if (Regex.IsMatch(eventData.FormatDescription() ?? "", SearchUseRegExp ? SearchString : Regex.Escape(SearchString), RegexOptions.IgnoreCase)) { eventList.Add(CreateEventInfo(eventData)); returnedEventsCounter--; } } eventData.Dispose(); } while (true); } return(new EventListDataItem[] { new EventListDataItem(new EventList { Events = eventList, ErrorCode = 0, ErrorMessage = "" }) }); } } catch (Exception e) { ModuleErrorSignalReceiver(ModuleErrorSeverity.DataLoss, ModuleErrorCriticality.Continue, e, $"Failed to query local {LogName ?? "NULL"} event log using {XPathQuery ?? "NULL"} XPath query: {e.Message}"); return(new EventListDataItem[] { new EventListDataItem(new EventList { Events = new List <EventInfo>(), ErrorCode = e.HResult, ErrorMessage = $"Failed to query local {LogName} event log using {XPathQuery ?? "NULL"} XPath query: {e.Message}" }) }); } }