public static EventLogRecord[] ReadEventLog(EventlogHandle handle, UInt32 dwLastRecordId, UInt32 nMaxRecords, string sqlQuery) { EventLogRecord[] result = null; EventAPI.EventLogRecord[] records = null; // new EventAPI.EventLogRecord[nMaxRecords]; UInt32 nRecordsReturned = 0; UInt32 dwError = EventAPI.ReadEventLog(handle.Handle, dwLastRecordId, nMaxRecords, sqlQuery, out nRecordsReturned, out records); if (dwError != 0) { Logger.Log(String.Format("Error: ReadEventLog [Code:{0}]", dwError), Logger.eventLogLogLevel); } if (nRecordsReturned > 0) { result = new EventLogRecord[nRecordsReturned]; int iRecord = 0; foreach (EventAPI.EventLogRecord record in records) { result[iRecord++] = new EventLogRecord(record); } } return result; }
/// <summary> /// The preferred constructor /// </summary> /// <param name="container">Back reference to the PlugInContainer</param> /// <param name="el">Reference to the log being viewed</param> public LogPropertiesPage(IPlugInContainer container, EventLogRecord el, IPlugIn plgin, StandardPage parentPage) : this() { this.pageID = "LogProperities"; this._container = container; this.el = el; this._plugin = plgin as EventlogPlugin; this._parentPage = parentPage; }
public override Task WriteAsync(EventLogRecord eventLogRecord) { if ((eventLogRecord.DataObject is object) && (eventLogRecord.DataByte == null) && string.IsNullOrEmpty(eventLogRecord.DataText)) { eventLogRecord.DataByte = Brimborium.Latrans.JSON.JsonSerializer.Serialize(eventLogRecord.DataObject); } var stream = this._Stream; if (stream is object) { ReadableLogUtil.WriteUtf8(eventLogRecord, stream); } return(Task.CompletedTask); }
public static void Write(EventLogRecord readableLog, Action <string> write) { write("-"); write("\n"); write(" lg: "); write(readableLog.LgId.ToString()); write("\n"); if (readableLog.DT != DateTime.MinValue) { write(" at: "); write(readableLog.DT.ToString("u")); write("\n"); } if (!string.IsNullOrEmpty(readableLog.Key)) { write(" ky: "); write(readableLog.Key !); write("\n"); } if (!string.IsNullOrEmpty(readableLog.TypeName)) { write(" ty: "); write(readableLog.TypeName !); write("\n"); } var data = readableLog.DataText; if (data is object) { write(" ln: "); write(data.Length.ToString()); write("\n"); bool newLineFound = false; for (int idx = 0; idx < data.Length; idx++) { char ch = data[idx]; if ((ch == '\r') || (ch == '\n')) { newLineFound = true; break; } } if (newLineFound) { write(" da: |"); write("\n"); var dataLines = data.Replace("\n", "\n "); write(" "); write(dataLines); write("\n"); } else { write(" da: "); write(data); write("\n"); } } }
// Module defining this command // Optional custom code for this activity /// <summary> /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. /// </summary> /// <param name="context">The NativeActivityContext for the currently running activity.</param> /// <returns>A populated instance of System.Management.Automation.PowerShell</returns> /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks> protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context) { System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create(); System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments if (Content.Expression != null) { targetCommand.AddParameter("Content", Content.Get(context)); } if (EventLogRecord.Expression != null) { targetCommand.AddParameter("EventLogRecord", EventLogRecord.Get(context)); } if (Path.Expression != null) { targetCommand.AddParameter("Path", Path.Get(context)); } if (LiteralPath.Expression != null) { targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context)); } if (IncludeContext.Expression != null) { targetCommand.AddParameter("IncludeContext", IncludeContext.Get(context)); } if (To.Expression != null) { targetCommand.AddParameter("To", To.Get(context)); } return(new ActivityImplementationContext() { PowerShellInstance = invoker }); }
public override void Write(EventLogRecord eventLogRecord) { if ((eventLogRecord.DataObject is object) && (eventLogRecord.DataByte == null) && string.IsNullOrEmpty(eventLogRecord.DataText)) { var t = this._JsonSerializerFacade.Serialize(eventLogRecord.DataObject); eventLogRecord.TypeName = t.TypeName; eventLogRecord.DataByte = t.DataByte; } var stream = this._Stream; if (stream is object) { ReadableLogUtil.WriteUtf8(eventLogRecord, stream); //stream.Flush(); } }
public static string CreateDataItem(this EventLogRecord eventRecord, string workspaceId) { string dataItemTemplate = "<DataItem type=\"System.Event.LinkedData\" time=\"{EventTimeUTC}\" sourceHealthServiceId=\"{WorkspaceId}\"><EventOriginId>{7C384BE3-8EBD-4B86-A392-357AA34750C5}</EventOriginId><PublisherId>{{ProviderGuid}}</PublisherId><PublisherName>{Provider}</PublisherName><EventSourceName>{EventSource}</EventSourceName><Channel>{Channel}</Channel><LoggingComputer>{Computer}</LoggingComputer><EventNumber>{EventId}</EventNumber><EventCategory>{EventCategory}</EventCategory><EventLevel>{EventLevel}</EventLevel><UserName>N/A</UserName><RawDescription></RawDescription><LCID>1033</LCID><CollectDescription>True</CollectDescription><EventData><DataItem type=\"System.XmlData\" time=\"{EventTimeUTC}\" sourceHealthServiceId=\"{WorkspaceId}\">{EventData}</DataItem></EventData><EventDisplayNumber>{EventId}</EventDisplayNumber><EventDescription></EventDescription><ManagedEntityId>{D056ADDA-9675-7690-CC92-41AA6B90CC05}</ManagedEntityId><RuleId>{1F68E37D-EC73-9BD3-92D5-C236C995FA0A}</RuleId></DataItem>\r\n"; DateTime timeCreated = (DateTime)eventRecord.TimeCreated; string tempWinEvent = dataItemTemplate; tempWinEvent = tempWinEvent.Replace("{WorkspaceId}", workspaceId); tempWinEvent = tempWinEvent.Replace("{ProviderGuid}", (eventRecord.ProviderId ?? Guid.Empty).ToString()); tempWinEvent = tempWinEvent.Replace("{Provider}", eventRecord.ProviderName); tempWinEvent = tempWinEvent.Replace("{EventSource}", eventRecord.ProviderName); tempWinEvent = tempWinEvent.Replace("{Channel}", eventRecord.LogName ?? "Unknown"); tempWinEvent = tempWinEvent.Replace("{Computer}", eventRecord.MachineName); tempWinEvent = tempWinEvent.Replace("{EventId}", eventRecord.Id.ToString()); tempWinEvent = tempWinEvent.Replace("{EventCategory}", (eventRecord.Task ?? 0).ToString()); tempWinEvent = tempWinEvent.Replace("{EventLevel}", (eventRecord.Level ?? 0).ToString()); tempWinEvent = tempWinEvent.Replace("{EventTimeUTC}", $"{ timeCreated.ToUniversalTime():yyyy-MM-ddTHH:mm:ss.ffffffZ}"); tempWinEvent = tempWinEvent.Replace("{EventData}", RetrieveExtendedData(eventRecord.ToXml())); return(tempWinEvent); }
public void Write(EventLogRecord eventLogRecord) { if (eventLogRecord.DT == System.DateTime.MinValue) { eventLogRecord.DT = this._SystemClock.UtcNow; } var utcNow = eventLogRecord.DT; if ((eventLogRecord.DataObject is object) && (eventLogRecord.DataByte == null) && string.IsNullOrEmpty(eventLogRecord.DataText)) { var t = this._JsonSerializerFacade.Serialize(eventLogRecord.DataObject); eventLogRecord.TypeName = t.TypeName; eventLogRecord.DataByte = t.DataByte; } var storageFile = this._StorageFile; var nextStorageFile = this.EnsureStorageFile(utcNow, storageFile); if (nextStorageFile is object) { nextStorageFile.Initialize(); var oldStorageFile = System.Threading.Interlocked.CompareExchange( ref this._StorageFile, nextStorageFile, storageFile); nextStorageFile.Write(eventLogRecord); if (ReferenceEquals(oldStorageFile, storageFile)) { this._LastWrite.Next((innerState) => { innerState?.Dispose(); return(Task.CompletedTask); }, storageFile); } } else if (storageFile is object) { storageFile.Write(eventLogRecord); } }
private void btnCopy_Click(object sender, EventArgs e) { try { string eventData = "Event Type: {0}" + "\n" + "Event Source: {1}" + "\n" + "Event Category: {2}" + "\n" + "Event ID: {3}" + "\n" + "Date: {4}" + "\n" + "Time: {5}" + "\n" + "User: {6}" + "\n" + "Computer: {7}" + "\n" + "Description:" + "\n" + "{8}"; string clipBoardData = string.Empty; // load the selected row if (_eventsListView.SelectedItems.Count == 0) { return; } EventLogRecord el = _eventsListView.SelectedItems[0].Tag as EventLogRecord; if (el != null) { EventAPI.EventLogRecord eventRecord = el.Record; DateTime eventTime = EventUtils.Time_T2DateTime(eventRecord.dwEventDateTime); eventTime = eventTime.ToLocalTime(); // copy fields to clipboard clipBoardData = string.Format(eventData, eventRecord.pszEventType, eventRecord.pszEventSource, eventRecord.pszEventCategory, eventRecord.dwEventSourceId.ToString(), eventTime.ToString("MM/dd/yyyy"), eventTime.ToString("hh:mm:ss"), eventRecord.pszUser, eventRecord.pszComputer, eventRecord.pszDescription); } if (clipBoardData != "") { if (Clipboard.ContainsText()) { Clipboard.Clear(); } Clipboard.SetText(clipBoardData); } } catch (Exception ex) { Logger.Log(ex.ToString(), Logger.LogLevel.Error); } }
public void WriteNewtonsoftStream() { var sb = new StringBuilder(4096); using (var sw = new StringWriter(sb)) { for (int idx = 1; idx < cnt; idx++) { var d = lstWriteD[idx - 1]; var json = Newtonsoft.Json.JsonConvert.SerializeObject(d); var r = new EventLogRecord() { LgId = (ulong)idx, DT = dt.AddHours(idx), Key = idx.ToString(), TypeName = "D", DataText = json }; lstWriteRL.Add(r); ReadableLogUtil.Write(r, sw); } sw.Close(); } txtWriteNewtonsoftStream = sb.ToString(); var log1 = sb.ToString(); #if output System.Console.Out.WriteLine(log1.Length); #endif using (var sr = new StringReader(log1)) { ReadableLogUtil.Read(sr, (lstReadRL, lstReadD), (state, r) => { state.lstReadRL.Add(r); var d = Newtonsoft.Json.JsonConvert.DeserializeObject <Dummy>(r.DataText); state.lstReadD.Add(d); }); } }
public static IDictionary <string, object> Deserialize(this EventLogRecord e, bool includeBookmark = false) { var beforeCulture = Thread.CurrentThread.CurrentCulture; try { var sanitizedXmlString = XmlScrubber.VerifyAndRepairXml(e.ToXml()); var xe = XElement.Parse(sanitizedXmlString); var systemData = xe.Element(ElementNames.System); Dictionary <string, object> instance = XmlEventParseHelpers.ConvertSystemPropertiesToDictionary(xe); var eventData = xe.Element(ElementNames.EventData); var userData = xe.Element(ElementNames.UserData); // Convert the EventData to named properties if (eventData != null) { instance["EventData"] = XmlEventParseHelpers.ParseEventData(eventData); } // Convert the EventData to named properties if (userData != null) { instance["UserData"] = XmlEventParseHelpers.ParseUserData(userData); } if (includeBookmark) { instance.Add("BookmarkChannel", GetBookmarkChannel(e.Bookmark)); } return(instance); } finally { Thread.CurrentThread.CurrentCulture = beforeCulture; } }
public LogPropertiesDlg(IPlugInContainer container, StandardPage parentPage, EventlogPlugin plugin, ListView lvEvents, EventLogRecord el, EventFilter ef, string pageID) : base(container, parentPage) { InitializeComponent(); btnApply.Enabled = true; this.DataChanged = true; _plugin = plugin; _container = container; this._parentPage = parentPage; _eventsListView = lvEvents; _el = el; _ef = ef; sShowPage = pageID; if (parentPage != null && parentPage.LMCTree != null && parentPage.LMCTree.SelectedNode != null && !String.IsNullOrEmpty(parentPage.LMCTree.SelectedNode.Text)) { this.Text = parentPage.LMCTree.SelectedNode.Text + " " + "Properties"; } InitializePages(); }
private static void DisplayEventAndLogInformation(EventLogReader logReader) { for (EventRecord eventInstance = logReader.ReadEvent(); null != eventInstance; eventInstance = logReader.ReadEvent()) { Console.WriteLine("-----------------------------------------------------"); Console.WriteLine("Event ID: {0}", eventInstance.Id); Console.WriteLine("Publisher: {0}", eventInstance.ProviderName); try { Console.WriteLine("Description: {0}", eventInstance.FormatDescription()); } catch (EventLogException) { // The event description contains parameters, and no parameters were // passed to the FormatDescription method, so an exception is thrown. } // Cast the EventRecord object as an EventLogRecord object to // access the EventLogRecord class properties EventLogRecord logRecord = (EventLogRecord)eventInstance; Console.WriteLine("Container Event Log: {0}", logRecord.ContainerLog); } }
private IEnumerable <EventLogRecord> InnerReadEvents(EventInfo startEventInfo, EventInfo finishEventInfo, string[] shards, int batchCount) { var startRowNumber = eventLogPointerCreator.GetRowNumber(startEventInfo); var finishRowNumber = eventLogPointerCreator.GetRowNumber(finishEventInfo); var startEventPointer = eventLogPointerCreator.Create(startEventInfo); var getRowsBatchCount = batchCount / shards.Length; var rowKeys = shards.Select(shard => eventLogPointerCreator.ChangeShard(startRowNumber, shard)).ToArray(); var rows1 = columnFamilyConnection.GetRowsExclusive(rowKeys, startEventPointer.ColumnName, getRowsBatchCount).ToDictionary(x => x.Key, x => x.Value); var rows2 = new Dictionary <string, Column[]>(); var needColumns2 = false; if (startRowNumber < finishRowNumber && rows1.Count(x => x.Value.Length < getRowsBatchCount) > 2) //todo подумать над константой { var rowKeys2 = shards.Select(shard => eventLogPointerCreator.ChangeShard(startRowNumber + 1, shard)).ToArray(); rows2 = columnFamilyConnection.GetRowsExclusive(rowKeys2, null, getRowsBatchCount).ToDictionary(x => x.Key, x => x.Value); needColumns2 = true; } var list = new List <IEnumerable <EventLogRecord> >(); foreach (var shard in shards) { var rowKey1 = eventLogPointerCreator.ChangeShard(startRowNumber, shard); var rowKey2 = eventLogPointerCreator.ChangeShard(startRowNumber + 1, shard); var columns1 = GetColumnsFromDict(rows1, rowKey1); var columns2 = GetColumnsFromDict(rows2, rowKey2); var columns = needColumns2 ? new[] { columns1, columns2 } : new[] { columns1 }; var eventLogRecords = GetEventsEnumerable(shard, startRowNumber, startEventPointer.ColumnName, finishRowNumber, columns, batchCount, getRowsBatchCount); list.Add(eventLogRecords); } IEnumerable <EventLogRecord> res = new EventLogRecord[0]; res = list.Aggregate(res, (current, x) => current.SortedMerge(x, (a, b) => a.StorageElement.EventInfo.CompareTo(b.StorageElement.EventInfo))); return(res); }
public static IDictionary <string, object> OptimizedDeserialize(this EventLogRecord e) { var beforeCulture = Thread.CurrentThread.CurrentCulture; try { string eventXml = e.ToXml(); var xe = XElement.Parse(eventXml); var eventData = xe.Element(ElementNames.EventData); var instance = XmlEventParseHelpers.ConvertSystemPropertiesToDictionary(xe); instance.Add("BookmarkChannel", GetBookmarkChannel(e.Bookmark)); if (eventData != null) { var eventDataProperties = XmlEventParseHelpers.ParseEventData(eventData); var namedProperties = eventDataProperties.ToDictionary(x => x.Key, x => x.Value); instance["EventData"] = namedProperties; } else { instance.Add("EventData", new Dictionary <string, object>()); } return(instance); } catch { return(Deserialize(e)); // Scrub only if any error occurs while deserializing. } finally { Thread.CurrentThread.CurrentCulture = beforeCulture; } }
public void Write(EventLogRecord eventLogRecord) { //this._Log.Enqueue() throw new NotImplementedException(); }
public static UInt32 ReadEventLog(IntPtr hEventLog, UInt32 dwLastRecordId, UInt32 nRecordsPerPage, string sqlQuery, out UInt32 pdwNumReturned, out EventLogRecord[] records) { UInt32 result = 0; records = null; pdwNumReturned = 0; IntPtr bufPtr = IntPtr.Zero; try { Logger.Log(String.Format( "ReadEventLog(hEventLog={0:X}, dwLastRecordId={1}, nRecordsPerPage={2}) called", hEventLog.ToInt32(), dwLastRecordId, nRecordsPerPage), Logger.eventLogLogLevel); result = PrivateEventAPI.LWIReadEventLog(hEventLog, dwLastRecordId, nRecordsPerPage, sqlQuery, out pdwNumReturned, out bufPtr); Logger.Log(String.Format( "ReadEventLog_after(result={0}, pdwNumReturned={1}, bufPtr={2:X})", result, pdwNumReturned, bufPtr.ToInt32()), Logger.eventLogLogLevel); if (pdwNumReturned > 0) { records = new EventLogRecord[pdwNumReturned]; IntPtr iter = bufPtr; for (int i = 0; i < pdwNumReturned && iter != IntPtr.Zero; i++) { records[i] = (EventLogRecord)Marshal.PtrToStructure(iter, typeof(EventLogRecord)); iter = (IntPtr)((int)iter + Marshal.SizeOf(typeof(EventLogRecord))); } } //this function produces a lot of output, so only run it at Debug level. LogEventLogRecords(records, Logger.eventLogLogLevel); } catch (Exception ex) { Logger.LogException("EventAPI.OpenEventLog", ex); if (result == 0) { result = 0xFFFFFFFF; } } //Marshal.FreeHGlobal(bufPtr); return result; }
internal EventRecordWrittenEventArgs(EventLogRecord record) { EventRecord = record; }
/// <summary> /// Return first event in time. /// </summary> /// <param name="mintue"></param> /// <returns></returns> public static bool MonitorWindowsEventLog(int mintue, string[] machines, string rpcUsername, string rpcPassword, out string result) { result = string.Empty; StringBuilder debugTrace = new StringBuilder(); debugTrace.AppendLine("$MonitorResult$"); int totalErrorCount = 0; foreach (var machine in machines) { debugTrace.AppendLine(""); string[] logs = new string[] { "Application", "System" }; foreach (string log in logs) { int errorCount = 0; debugTrace.AppendLine(string.Format("Start monitoring {0}[{1}] from {2}", machine, log, Environment.MachineName)); if (string.Compare(machine, Environment.MachineName, true) == 0) { EventLog myLog = new EventLog(); myLog.Log = log; List <string> errorList = new List <string>(); foreach (EventLogEntry entry in myLog.Entries) { //EventLogEntryType include: //Error //FailureAudit //Information //SuccessAudit //Warning string temp = string.Empty; if (entry.TimeGenerated.AddMinutes(mintue) > DateTime.Now && (entry.EntryType == EventLogEntryType.Error || entry.EntryType == EventLogEntryType.Warning)) { errorList.Add(machine + " |" + log + " |" + entry.EntryType.ToString() + " | " + entry.TimeWritten.ToString() + "\r\n" + entry.Message); errorCount++; totalErrorCount++; } } if (errorList.Count > 0) { debugTrace.AppendLine( string.Format("Found {0} errors on {1}[{2}]", errorList.Count, machine, log)); for (int i = 0; i < errorList.Count; i++) { debugTrace.AppendLine(string.Format("Error {0}: {1}", i + 1, errorList[i])); } } } else { string[] eventTypes = new string[] { "Warning", "Error" }; string eventLevel = "4"; foreach (var eventType in eventTypes) { switch (eventType) { case "Information": eventLevel = "4"; break; case "Warning": eventLevel = "3"; break; case "Error": eventLevel = "2"; break; } String queryString = string.Format("*[System/Level={0}]", eventLevel); SecureString pw = new SecureString(); for (int i = 0; i < rpcPassword.Length; i++) { pw.AppendChar(rpcPassword[i]); } pw.MakeReadOnly(); EventLogSession session = new EventLogSession( machine, // Remote Computer Machine Name "", // Domain rpcUsername, // Username pw, SessionAuthentication.Default); pw.Dispose(); // Query the Application log on the remote computer. EventLogQuery query = new EventLogQuery(log, PathType.LogName, queryString); query.Session = session; try { EventLogReader logReader = new EventLogReader(query); List <EventRecord> errorList = new List <EventRecord>(); for (EventRecord eventInstance = logReader.ReadEvent(); null != eventInstance; eventInstance = logReader.ReadEvent()) { if (((DateTime)eventInstance.TimeCreated).AddMinutes(mintue) > DateTime.Now) //&& (eventInstance.LevelDisplayName == EventLogEntryType.Error || eventInstance.LevelDisplayName == EventLogEntryType.Warning)) { errorList.Add(eventInstance); errorCount++; totalErrorCount++; } } if (errorList.Count > 0) { StringBuilder sb = new StringBuilder(); debugTrace.AppendLine( string.Format("Found {0} errors on {1}[{2}]", errorList.Count, machine, log)); for (int i = 0; i < errorList.Count; i++) { EventLogRecord logEntry = (EventLogRecord)errorList[i]; debugTrace.AppendLine(string.Format("Error {0}: {1}", i + 1, Environment.MachineName + " |" + machine + " |" + log + " |" + logEntry.LevelDisplayName + " | " + logEntry.TimeCreated)); debugTrace.AppendLine(errorList[i].FormatDescription()); debugTrace.AppendLine(logEntry.ContainerLog); } } //else //{ // debugTrace.AppendLine(string.Format("No error found on {0}", machine)); //} } catch (Exception e) { result = string.Format("Exception {0}[{1}]: {2}", machine, log, e.Message); return(false); } } } if (errorCount == 0) { debugTrace.AppendLine(string.Format("No error found on machine {0}[{1}]", machine, log)); } } } if (totalErrorCount > 0) { debugTrace.Replace("$MonitorResult$", "Total count of error: " + totalErrorCount); result = debugTrace.ToString(); return(false); } else { //debugTrace.Replace("$MonitorResult$", "No error found on all servers"); result = "No error found on all servers";//debugTrace.ToString(); return(true); } }
private static void LogEventLogRecords(EventLogRecord[] records, Logger.LogLevel level) { //save a bit of CPU if the eventlog log has been silenced if (Logger.currentLogLevel < level) { return; } string result = "EventLogRecords[]: "; if (records == null) { result += "null"; } else if (records.Length == 0) { result += " Count=0"; } else { int i = 0; foreach (EventLogRecord record in records) { result += String.Format("\n\t{0}: recordID={1}, eventID={2}, eventType={3}, eventTime={4}", i, record.dwEventRecordId, record.pszEventType, record.dwEventDateTime, record.pszEventCategory); result += String.Format("\n\t\tsource: {0}, user: {1}, computer: {2}", record.pszEventSource, record.pszUser, record.pszComputer); result += String.Format("\n\t\tdescription: {0}", record.pszDescription); result += String.Format("\n\t\tdata: {0}", record.pszData); i++; } } Logger.Log(result, level); }
public static void Write(EventLogRecord readableLog, TextWriter textWriter) { Write(readableLog, (string txt) => textWriter.Write(txt)); }
//private static readonly RecyclableMemoryStreamManager _RecyclableMemoryStreamManager = new RecyclableMemoryStreamManager(); public static void Read <TState>( TextReader textReader, TState state, Action <TState, EventLogRecord> read ) { var invariantCulture = (_InvariantCulture ??= System.Globalization.CultureInfo.InvariantCulture); StringBuilder sbValue = new StringBuilder(4096); // var stringComparer = StringComparer.Ordinal; int ch; EventLogRecord result = new EventLogRecord() { LgId = 0, DT = DateTime.MinValue, Key = null, TypeName = null, DataText = null, }; long ln = -1; ch = textReader.Read(); bool valid = true; while (ch >= 0) { // -\r\n if (CheckAndRead(ref ch, '-', textReader)) { if (ReadLineFeed(ref ch, textReader) >= 0 && ch >= 0) { while (valid && CheckAndRead(ref ch, ' ', textReader)) { // _lg:_ | _ln:_ if (valid && CheckAndRead(ref ch, 'l', textReader)) { // _lg:_ if (valid = CheckAndRead(ref ch, 'g', textReader)) { if (valid = CheckAndRead(ref ch, ':', textReader)) { if (valid = CheckAndRead(ref ch, ' ', textReader)) { sbValue.Clear(); ReadLineFeedExclude(ref ch, textReader, sbValue); if (ulong.TryParse(sbValue.ToString(), out var lgId)) { result.LgId = lgId; } continue; } } } // _ln:_ if (valid = CheckAndRead(ref ch, 'n', textReader)) { if (valid = CheckAndRead(ref ch, ':', textReader)) { if (valid = CheckAndRead(ref ch, ' ', textReader)) { sbValue.Clear(); ReadLineFeedExclude(ref ch, textReader, sbValue); if (long.TryParse(sbValue.ToString(), out var lclLn)) { ln = lclLn; } continue; } } } continue; } // _at:_ if (valid && CheckAndRead(ref ch, 'a', textReader)) { if (valid = CheckAndRead(ref ch, 't', textReader)) { if (valid = CheckAndRead(ref ch, ':', textReader)) { if (valid = CheckAndRead(ref ch, ' ', textReader)) { sbValue.Clear(); ReadLineFeedExclude(ref ch, textReader, sbValue); // TryParseExact FormatProvider // TryParseExact(string? s, string? format, IFormatProvider? provider, DateTimeStyles style, out DateTime result) if (DateTime.TryParseExact( sbValue.ToString(), "u", invariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out var dt)) { result.DT = dt; } continue; } } } continue; } // _ky:_ if (valid && CheckAndRead(ref ch, 'k', textReader)) { if (valid = CheckAndRead(ref ch, 'y', textReader)) { if (valid = CheckAndRead(ref ch, ':', textReader)) { if (valid = CheckAndRead(ref ch, ' ', textReader)) { sbValue.Clear(); ReadLineFeedExclude(ref ch, textReader, sbValue); result.Key = sbValue.ToString(); continue; } } } continue; } // _ty:_ if (valid && CheckAndRead(ref ch, 't', textReader)) { if (valid = CheckAndRead(ref ch, 'y', textReader)) { if (valid = CheckAndRead(ref ch, ':', textReader)) { if (valid = CheckAndRead(ref ch, ' ', textReader)) { sbValue.Clear(); ReadLineFeedExclude(ref ch, textReader, sbValue); result.TypeName = sbValue.ToString(); continue; } } } continue; } // _da:_ if (valid && CheckAndRead(ref ch, 'd', textReader)) { if (valid = CheckAndRead(ref ch, 'a', textReader)) { if (valid = CheckAndRead(ref ch, ':', textReader)) { if (valid = CheckAndRead(ref ch, ' ', textReader)) { string data; if (CheckAndRead(ref ch, '|', textReader)) { ReadLineFeed(ref ch, textReader); while (CheckAndRead(ref ch, ' ', textReader)) { if (CheckAndRead(ref ch, ' ', textReader)) { sbValue.Clear(); ReadLineFeedInclude(ref ch, textReader, sbValue); } } if ((sbValue.Length >= 2) && sbValue.ToString(sbValue.Length - 2, 2) == "\r\n") { sbValue.Remove(sbValue.Length - 2, 2); } else if ((sbValue.Length >= 1) && (sbValue[sbValue.Length - 1] == '\r') || (sbValue[sbValue.Length - 1] == '\n')) { sbValue.Remove(sbValue.Length - 1, 1); } data = sbValue.ToString(); } else { sbValue.Clear(); ReadLineFeedExclude(ref ch, textReader, sbValue); data = sbValue.ToString(); } // if (ln > 0) { if (data.Length == ln) { result.DataText = data; read(state, result); result = new EventLogRecord() { LgId = 0, DT = DateTime.MinValue, Key = null, TypeName = null, DataText = null, }; } else { valid = false; } ln = -1; } else { result.DataText = data; read(state, result); result = new EventLogRecord() { LgId = 0, DT = DateTime.MinValue, Key = null, TypeName = null, DataText = null, }; } continue; } } } continue; } // if (!valid) { break; } } // while ' ' } } // invalid if (!valid) { while (ch >= 0) { ch = textReader.Read(); if (ch == '\r' || ch == '\n') { ch = textReader.Read(); if (ch == '\r' || ch == '\n') { ch = textReader.Read(); } break; } } } } }
/// <summary> /// Displays the event information and log information on the console for /// all the events returned from a query. /// </summary> public List <TimeEntry> DisplayEventAndLogInformation(EventLogReader logReader) { TimeEntry time = null; DateTime now = DateTime.Now; Dictionary <string, TimeEntry> timetable = new Dictionary <string, TimeEntry>(); for (EventRecord eventdetail = logReader.ReadEvent(); eventdetail != null; eventdetail = logReader.ReadEvent()) { EventLogRecord logRecord = (EventLogRecord)eventdetail; DateTime eventTime = eventdetail.TimeCreated.Value; WinEvent eventId = (WinEvent)eventdetail.Id; string key = eventTime.ToString(AppConfig.DateFormat); // candidate for logout after midnight. if ((eventId == WinEvent.Shutdown || eventId == WinEvent.Logoff) && 0.0 <= eventTime.TimeOfDay.TotalHours && eventTime.TimeOfDay.TotalHours <= AppConfig.LogoutTolerance) { key = eventTime.AddDays(-1).ToString(AppConfig.DateFormat); } if (!timetable.TryGetValue(key, out time)) { time = new TimeEntry(); timetable.Add(key, time); } switch (eventId) { case WinEvent.Startup: case WinEvent.Logon: time.TimeIn = eventTime; break; case WinEvent.Logoff: case WinEvent.Shutdown: if (time.TimeOut < eventTime) { time.TimeOut = eventTime; } break; } } // note: logic below will only works with sorted in ascending order log entries! foreach (KeyValuePair <string, TimeEntry> e in timetable.ToList()) { time = e.Value; // calculate logout time for today if (time.IsSameDay(DateTime.Today)) { time.TimeOut = time.OutTime; if (time.TimeOut < DateTime.Now) { time.TimeOut = DateTime.Now; } this.Add(time); break; } // strip invalid entries if (time.IsNotValid()) { continue; } this.Add(time); if (time.OverTime > 0) { _totalOvertime += time.OverTime; } } if (!AppConfig.isAscending()) { this.Sort(delegate(TimeEntry firstPair, TimeEntry nextPair) { return(nextPair.CompareTo(firstPair)); }); } return(this); }
/// <summary> /// Callback method that gets executed when an event is /// reported to the subscription. /// </summary> private void EventRead(object obj, EventRecordWrittenEventArgs arg) { EventLogWatcher watcher = obj as EventLogWatcher; EventLogRecord evtlog = (EventLogRecord)arg.EventRecord; EventLogException evtex = (EventLogException)arg.EventException; if (evtlog == null) { if (evtex == null) { Log.Error("No event log info!?"); } else { Log.Error("No event log info, received exception: " + arg.EventException.Message); } return; } int eventId; long recordId; long keywords; string machineName; DateTime created; string providerName; int processId; string logName; string logLevel; IList <object> evtdata = null; try { // without this synchronization we sometimes get corrupted evtlog // data with invalid handle (EventLogException) lock (eventLock) { eventId = evtlog.Id; recordId = evtlog.RecordId.GetValueOrDefault(0); keywords = evtlog.Keywords.GetValueOrDefault(0); machineName = evtlog.MachineName; created = evtlog.TimeCreated.GetValueOrDefault(DateTime.Now); providerName = evtlog.ProviderName; processId = evtlog.ProcessId.GetValueOrDefault(0); logName = evtlog.LogName; logLevel = evtlog.LevelDisplayName; // NOTE: may be just this line needs synchronization? if (evtsel != null) { evtdata = evtlog.GetPropertyValues(evtsel); } } } catch (EventLogException ex) { Log.Error("Unable to access log info: " + ex.Message); return; } catch (Exception ex) { Log.Error("Unable to access log info: " + ex.Message); return; } // just verbose debug info about received event if (Log.Level == EventLogEntryType.Information) { // debug info Log.Info("EventLog[" + recordId + "@" + Name + "]: new log event received"); // more debug info for (int i = 0; evtdata != null && i < evtdata.Count; i++) { EventLogParserData evtregex = evtregexs[i]; if (evtdata[i] != null) { if (evtdata[i].GetType().IsArray) { foreach (string item in (object[])evtdata[i]) { Log.Info("EventLog[" + recordId + "@" + Name + "][" + evtregex.XPath + "](" + evtdata[i].GetType() + "):" + item.ToString()); } } else { Log.Info("EventLog[" + recordId + "@" + Name + "][" + evtregex.XPath + "](" + evtdata[i].GetType() + "):" + evtdata[i].ToString()); } } else { Log.Info("EventLog[" + recordId + "@" + Name + "][" + evtregex.XPath + "]: NULL!!!"); } } } EventEntry evt = new EventEntry(this, created, machineName, arg); foreach (EventDataElement item in evtdata_before) { if (item.Overwrite || !evt.HasProcData(item.Name)) { evt.SetProcData(item.Name, item.Value); } } // set basic event properties evt.SetProcData("Event.EventId", eventId.ToString()); evt.SetProcData("Event.RecordId", recordId.ToString()); evt.SetProcData("Event.Keywords", keywords.ToString()); // machine name and time created already set in EventEntry constructor //evt.SetProcData("Event.MachineName", machineName); //evt.SetProcData("Event.TimeCreated", created.ToString()); evt.SetProcData("Event.ProviderName", providerName); evt.SetProcData("Event.ProcessId", processId.ToString()); evt.SetProcData("Event.LogName", logName); evt.SetProcData("Event.LogLevel", logLevel); IList <string> evtregexdata = new List <string>(); // ISet is not really better for small number of elements foreach (EventLogParserData evtregex in evtregexs) { foreach (Tuple <string, string> item in GetXPathData(evtdata[evtregex.Index], evtregex.Regex)) { string key = item.Item1 != null ? item.Item1 : evtregex.Id; evt.SetProcData("Event." + key, item.Item2); evtregexdata.Add(item.Item1 != null ? item.Item1 : evtregex.Id); } } foreach (KeyValuePair <string, EventDataElement> item in evtdata_match) { if (evtregexdata.Contains(item.Key)) { if (item.Value.Overwrite || !evt.HasProcData(item.Value.Name)) { evt.SetProcData(item.Value.Name, item.Value.Value); } } } foreach (EventDataElement item in evtdata_after) { if (item.Overwrite || !evt.HasProcData(item.Name)) { evt.SetProcData(item.Name, item.Value); } } // Event.EventData (NOTE: use EventData processor to parse event XML data) Log.Info("EventLog[" + recordId + "->" + evt.Id + "@" + Name + "] queued message from " + machineName); #if DEBUG if (Log.Level == EventLogEntryType.Information) { Log.Info("EventLog[" + recordId + "->" + evt.Id + "@" + Name + "] " + evt.ProcData.Count + " properties"); foreach (var item in evt.ProcData) { Log.Info("EventLog[" + recordId + "->" + evt.Id + "@" + Name + "]: " + item.Key + " = " + item.Value); } } #endif equeue.Produce(evt, Processor); }
public virtual void Write(EventLogRecord eventLogRecord) { }