コード例 #1
0
        public TestEventData(int eventIndex, TraceEvent traceEvent)
        {
            Index = eventIndex;

            StringValue = (string)traceEvent.PayloadByName("StringValue");
            IntValue    = (int)traceEvent.PayloadByName("IntValue");
        }
コード例 #2
0
ファイル: ETWRegistrant.cs プロジェクト: Zedfa/Core
        private void AddTraceEventToTraceList(TraceEvent e)
        {
            var level = 2;

            switch (e.Level)
            {
            case TraceEventLevel.Always:
            case TraceEventLevel.Verbose:
            case TraceEventLevel.Informational:
                level = 2;
                break;

            case TraceEventLevel.Critical:
            case TraceEventLevel.Error:
                level = 1;
                break;

            case TraceEventLevel.Warning:
                level = 3;
                break;
            }
            var data  = (string)e.PayloadByName("data");
            var trace = new TraceDto
            {
                Message  = e.FormattedMessage,
                Level    = level,
                TraceKey = (string)e.PayloadByName("traceKey") ?? string.Empty,
                Writer   = (string)e.PayloadByName("writer") ?? string.Empty,
                Data     = data != null?Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(data) : null
            };

            AddTraceToTraceList(trace);
        }
コード例 #3
0
 public FileIoEvent(TraceEvent eventData)
 {
     Irp         = eventData.PayloadByName("Irp").ToString();
     Process     = eventData.ProcessName;
     PID         = eventData.ProcessID;
     Time        = eventData.TimeStamp;
     FullPath    = eventData.PayloadByName("FileName") as string;
     RequestType = eventData.TaskName;
 }
コード例 #4
0
ファイル: WmiExecAsync.cs プロジェクト: Alois-xx/WMIWatcher
 public WmiExecAsync(TraceEvent @event) : base(@event)
 {
     Operation = (int)@event.ID switch
     {
         WMIProviderDefinitions.WMI_Activity_ExecAsync => WMIOperation.ExecAsync,
         _ => throw new InvalidOperationException($"Event with ID {WMIProviderDefinitions.WMI_Activity_ExecAsync} expected. But got: {@event.ID}")
     };
     GroupOperationId = (int)@event.PayloadByName("GroupOperationId");
     WmiOperation     = (string)@event.PayloadByName("Operation");
     ProviderName     = (string)@event.PayloadByName("ProviderName");
 }
コード例 #5
0
ファイル: Commands.cs プロジェクト: begemod/dotNext2016spb
    private void OnNewEvent(
        List <OperationData> operations,
        Dictionary <int, double> opStartTimeStamps,
        Dictionary <int, OperationData> pendingOps,
        TraceEvent data)
    {
        if (data.EventName == "ServiceChannelCall/Start")
        {
            opStartTimeStamps[data.ThreadID] = data.TimeStampRelativeMSec;
        }
        if (data.EventName == "ClientRuntime/OperationPrepared")
        {
            string action       = (string)data.PayloadByName("Action");
            string contractName = (string)data.PayloadByName("ContractName");

            action = action.Substring(action.IndexOf(contractName) + contractName.Length + 1);

            var op = new OperationData
            {
                Name      = action,
                Contract  = contractName,
                TimeStamp = data.TimeStampRelativeMSec
            };

            pendingOps[data.ThreadID] = op;
        }
        if (data.EventName == "ServiceChannelCall/Stop")
        {
            // Find pending OP by thred ID
            OperationData op;
            if (!pendingOps.TryGetValue(data.ThreadID, out op))
            {
                return;
            }

            // Find start time by thread ID
            double startTime;
            if (!opStartTimeStamps.TryGetValue(data.ThreadID, out startTime))
            {
                return;
            }

            double duration = data.TimeStampRelativeMSec - startTime;
            op.Duration += TimeSpan.FromMilliseconds(duration);

            operations.Add(op);
            pendingOps.Remove(data.ThreadID);
            opStartTimeStamps.Remove(data.ThreadID);
        }
    }
コード例 #6
0
 public GroupPolicyAction(TraceEvent activityStartEvent)
 {
     ActivityId = activityStartEvent.ActivityID;
     Mode =
         GroupPolicyDomainKnowledge.MeasurePolicyApplicationMode(
             (bool) activityStartEvent.PayloadByName("IsBackgroundProcessing"),
             (bool) activityStartEvent.PayloadByName("IsAsyncProcessing"));
     Trigger =
         GroupPolicyDomainKnowledge.ResolvePolicyApplicationTrigger(
             (int) activityStartEvent.ID);
     ReasonForSync =
         (ReasonForSync) (int) activityStartEvent.PayloadByName("ReasonForSyncProcessing");
     Scope =
         GroupPolicyDomainKnowledge.MeasureGpoScope(
             (int) activityStartEvent.PayloadByName("IsMachine"));
 }
コード例 #7
0
ファイル: Form1.cs プロジェクト: brianstringfellow/EtwViewer
        private void OnEtwEvent(TraceEvent traceEvent)
        {
            JObject row = new JObject();
            string  pre = "#";

            AddFieldData(row, pre + nameof(traceEvent.ProviderName), traceEvent.ProviderName);
            AddFieldData(row, pre + nameof(traceEvent.EventName), traceEvent.EventName);
            AddFieldData(row, pre + nameof(traceEvent.TaskName), traceEvent.TaskName);
            AddFieldData(row, pre + nameof(traceEvent.OpcodeName), traceEvent.OpcodeName);
            AddFieldData(row, pre + nameof(traceEvent.TimeStamp), traceEvent.TimeStamp.ToString("o"));
            AddFieldData(row, pre + nameof(traceEvent.FormattedMessage), traceEvent.FormattedMessage);

            foreach (var payloadKey in traceEvent.PayloadNames)
            {
                string payloadValue;
                try
                {
                    payloadValue = traceEvent.PayloadByName(payloadKey).ToString();
                }
                catch (Exception)
                {
                    payloadValue = "Error extracting payload";
                }

                AddFieldData(row, payloadKey, payloadValue);
            }

            string script = $"addRow({row})";

            _chromiumWebBrowser.GetMainFrame().ExecuteJavaScriptAsync(script);
        }
コード例 #8
0
ファイル: Extensions.cs プロジェクト: zdzhjx/etrace
        public static string GetFieldByName(this TraceEvent e, string field)
        {
            if (field == "Event")
            {
                return(e.EventName);
            }
            if (field == "PID")
            {
                return(e.ProcessID.ToString());
            }
            if (field == "TID")
            {
                return(e.ThreadID.ToString());
            }
            if (field == "Time")
            {
                return(e.TimeStamp.ToString());
            }

            object value = e.PayloadByName(field);

            if (value != null)
            {
                return(value.ToString());
            }
            else
            {
                return("<null>");
            }
        }
コード例 #9
0
 private void HandleEtwEvent(TraceEvent eventData)
 {
     if ((int)eventData.ID == EtwSource.ReplyEventId)
     {
         var data = eventData.PayloadByName("data") as byte[];
         replyData = data.ConvertTo <ReplyData>();
         replyReceived.Set();
     }
 }
コード例 #10
0
        private static object GetPayloadValue(TraceEvent evt, string payloadName)
        {
            var result = evt.PayloadByName(payloadName);

            if (result == null)
            {
                throw new NoNullAllowedException($"Payload \"{payloadName}\" doesn't exist in event \"{evt.EventName}\" ");
            }
            return(result);
        }
コード例 #11
0
        public WmiDisconnect(TraceEvent @event) : base(@event)
        {
            OperationId = (int)@event.ID switch
            {
                WMIProviderDefinitions.WMI_Activity_Disconnect => (int)@event.PayloadByName("OperationId"),
                _ => throw new InvalidOperationException($"Event with ID {WMIProviderDefinitions.WMI_Activity_Disconnect} expected. But got: {@event.ID}")
            };

            Operation = WMIOperation.Disconnect;
        }
    }
コード例 #12
0
ファイル: EtwServer.cs プロジェクト: ypog07/dotnext2017spb
 private void HandleEtwEvent(TraceEvent eventData)
 {
     if ((int)eventData.ID == EtwSource.RequestEventId)
     {
         var data      = eventData.PayloadByName("data") as byte[];
         var inputData = data.ConvertTo <InputData>();
         var reply     = ServerLogic.Convert(inputData);
         var replyBuf  = ByteArray.CreateFrom(reply);
         EtwSource.Instance.SendReplyData(replyBuf);
     }
 }
コード例 #13
0
ファイル: Program.cs プロジェクト: zdzhjx/etrace
        private static void ProcessEvent(TraceEvent e)
        {
            ++processedEvents;

            if (options.ProcessID != -1 && options.ProcessID != e.ProcessID)
            {
                return;
            }
            if (options.ThreadID != -1 && options.ThreadID != e.ThreadID)
            {
                return;
            }
            if (options.Events.Count > 0 && !options.Events.Contains(e.EventName))
            {
                return;
            }

            if (options.ParsedRawFilter != null)
            {
                string s = e.AsRawString();
                if (options.ParsedRawFilter.IsMatch(s))
                {
                    eventProcessor.TakeEvent(e, s);
                    ++notFilteredEvents;
                }
            }
            else if (options.ParsedFilters.Count > 0)
            {
                foreach (var filter in options.ParsedFilters)
                {
                    string payloadName = filter.Key;
                    Regex  valueRegex  = filter.Value;

                    object payloadValue = e.PayloadByName(payloadName);
                    if (payloadValue == null)
                    {
                        continue;
                    }

                    if (valueRegex.IsMatch(payloadValue.ToString()))
                    {
                        eventProcessor.TakeEvent(e);
                        ++notFilteredEvents;
                        break;
                    }
                }
            }
            else
            {
                eventProcessor.TakeEvent(e);
                ++notFilteredEvents;
            }
        }
コード例 #14
0
            private bool IsPayloadMatch(TraceEvent e)
            {
                bool result = false;

                object payloadValue = e.PayloadByName(Key);

                if (payloadValue != null)
                {
                    result = Value.IsMatch(payloadValue.ToString());
                }

                return(result);
            }
コード例 #15
0
        internal static LogMessage Load(TraceEvent request)
        {
            var(arguments, message) = LoadArguments((string)request.PayloadByName("ArgumentsJson"));
            var     eventIdStr = (string)request.PayloadByName("EventId");
            EventId eventId    = default;

            if (int.TryParse(eventIdStr, out var id))
            {
                eventId = new EventId(id);
            }
            else
            {
                eventId = new EventId(0, eventIdStr);
            }

            return(new LogMessage(
                       request.TimeStamp,
                       loggerName: (string)request.PayloadByName("LoggerName"),
                       eventId: eventId,
                       level: (LogLevel)(int)request.PayloadByName("Level"),
                       arguments: arguments,
                       message: message));
        }
コード例 #16
0
        private static void ExtractPayloadData(this TraceEvent traceEvent, TraceTelemetry telemetry)
        {
            Debug.Assert(telemetry != null, "Should have received a valid TraceTelemetry object");

            if (traceEvent.PayloadNames == null)
            {
                return;
            }

            foreach (string payloadName in traceEvent.PayloadNames)
            {
                telemetry.AddProperty(payloadName, traceEvent.PayloadByName(payloadName).ToString());
            }
        }
コード例 #17
0
 public void addData(TraceEvent data)
 {
     if (data.PayloadNames.Contains("PID"))
     {
         string ProcessId = data.PayloadByName("PID").ToString();
         if (findPID(ProcessId))
         {
             Parallel.Invoke(() => updateTableRow(data, ProcessId));
         }
         else
         {
             Parallel.Invoke(() => addNewTableData(data, ProcessId));
         }
     }
 }
コード例 #18
0
        void ProcessTraceEvent(TraceEvent traceEvent)
        {
            lastTimeEventWasReceivedUtc = DateTime.UtcNow;

            if (traceEvent.ProcessID == currentProcessId)
            {
                return;
            }

            if ((ushort)traceEvent.ID == DCStartInitEventId)
            {
                Debug.Assert(!processAppDomainsMap.ContainsKey(traceEvent.ProcessID));
                processAppDomainsMap.Add(traceEvent.ProcessID, new List <AppDomainInfo>());
            }
            else if ((ushort)traceEvent.ID == AppDomainDCStartEventId)
            {
                Debug.Assert(processAppDomainsMap.ContainsKey(traceEvent.ProcessID));
                processAppDomainsMap[traceEvent.ProcessID].Add(new AppDomainInfo()
                {
                    Id   = (long)traceEvent.PayloadByName("AppDomainID"),
                    Name = (string)traceEvent.PayloadByName("AppDomainName")
                });
            }
        }
コード例 #19
0
        public override void TraceEventAvailable(TraceEvent eventData)
        {
            try
            {
                var irp = eventData.PayloadByName("Irp").ToString();

                if (String.IsNullOrEmpty(irp))
                {
                    return;
                }


                if (eventData.TaskName == operationEnd)
                {
                    if (_operations.ContainsKey(irp))
                    {
                        var fileIo = _operations[irp];
                        _operations.Remove(irp);

                        var status = eventData.PayloadByName(payloadStatus) as int?;
                        fileIo.Status = status ?? -1;
                        fileIo.Name   = Path.GetFileName(fileIo.FullPath);
                        _completed(fileIo);
                    }
                }
                else
                {
                    var fileIo = new FileIoEvent(eventData);
                    _operations[fileIo.Irp] = fileIo;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #20
0
        public override void TraceEventAvailable(TraceEvent eventData)
        {
            if (eventData.Opcode == TraceEventOpcode.Start)
            {
                var processName = eventData.PayloadByName(PayloadImageName) as string;

                _completed(new ProcessStartEvent
                {
                    Name      = processName,
                    Pid       = eventData.ProcessID,
                    StartTime = eventData.TimeStamp
                });

                return;
            }
        }
コード例 #21
0
 private static void Print(TraceEvent data)
 {
     if (string.IsNullOrEmpty(data.FormattedMessage))
     {
         String message = data.EventName + ":";
         foreach (String name in data.PayloadNames)
         {
             message += " " + name + " - " + data.PayloadByName(name);
         }
         Console.WriteLine(message);
     }
     else
     {
         Console.WriteLine(data.FormattedMessage);
     }
 }
コード例 #22
0
        private static IDictionary <string, string> GetPayloadProperties(TraceEvent data)
        {
            var payLoadProperties = new Dictionary <string, string>();

            foreach (var payLoad in data.PayloadNames)
            {
                var payLoadData = data.PayloadByName(payLoad).ToString();
                if (!payLoadProperties.ContainsKey(payLoad))
                {
                    payLoadProperties.Add(payLoad, payLoadData);
                }
                else
                {
                    payLoadProperties[payLoad] = payLoadData;
                }
            }

            return(payLoadProperties);
        }
コード例 #23
0
 public static bool MatchProcessName(TraceEvent evt, TraceSourceManager source, string processName)
 {
     if (source.IsWindows)
     {
         if (!processName.Equals(evt.ProcessName, StringComparison.OrdinalIgnoreCase))
         {
             return(CompareResult.Mismatch);
         }
     }
     else
     {
         // 15 characters is the maximum length of a process name in Linux kernel event payload
         if (processName.Length < 15)
         {
             if (!processName.Equals(evt.ProcessName, StringComparison.OrdinalIgnoreCase))
             {
                 return(CompareResult.Mismatch);
             }
         }
         else
         {
             if (evt.PayloadByName("FileName") == null)
             {
                 // match the first 15 characters only if FileName field is not present in the payload
                 if (!processName.Substring(0, 15).Equals(evt.ProcessName, StringComparison.OrdinalIgnoreCase))
                 {
                     return(CompareResult.Mismatch);
                 }
             }
             else
             {
                 // match the full process name by extracting the file name
                 string filename = (string)GetPayloadValue(evt, "FileName");
                 if (!processName.Equals(Path.GetFileName(filename)))
                 {
                     return(CompareResult.Mismatch);
                 }
             }
         }
     }
     return(CompareResult.Match);
 }
コード例 #24
0
ファイル: AffectedKeys.cs プロジェクト: Evlikat/incinerate
 public AffectedKeys(TraceEvent traceEvent)
     : this()
 {
     string keyName = (string)traceEvent.PayloadByName("KeyName");
     if (!String.IsNullOrEmpty(keyName))
     {
         AffectedRegKeys.Add(ReplaceGuids(keyName));
     }
     string valueName = (string)traceEvent.PayloadByName("ValueName");
     if (!String.IsNullOrEmpty(valueName))
     {
         AffectedRegValues.Add(ReplaceGuids(valueName));
     }
     int? sPort = (int?)traceEvent.PayloadByName("sport");
     if (sPort != null)
     {
         AffectedSourcePorts.Add((UInt16)(sPort.Value));
     }
     int? dPort = (int?)traceEvent.PayloadByName("dport");
     if (dPort != null)
     {
         AffectedDestinationPorts.Add((UInt16)(dPort.Value));
     }
     if (!traceEvent.EventName.Contains("IPV6"))
     {
         int? sAddr = (int?)traceEvent.PayloadByName("saddr");
         if (sAddr != null)
         {
             AffectedSourceAddresses.Add(sAddr.Value);
         }
         int? dAddr = (int?)traceEvent.PayloadByName("daddr");
         if (dAddr != null)
         {
             AffectedDestinationAddresses.Add(dAddr.Value);
         }
     }
 }
コード例 #25
0
 private static string GetFunction(TraceEvent traceEvent)
 {
     return(traceEvent.PayloadByName("Function") as string);
 }
コード例 #26
0
ファイル: WcfMonitor.cs プロジェクト: begemod/dotNext2016spb
        private void OnNewEvent(TraceEvent data)
        {
            if (data.EventName == "ServiceChannelCall/Start")
            {
                opStartTimeStamps[data.ThreadID] = data.TimeStampRelativeMSec;
            }
            if (data.EventName == "ClientRuntime/OperationPrepared")
            {
                string action       = (string)data.PayloadByName("Action");
                string contractName = (string)data.PayloadByName("ContractName");

                action = action.Substring(action.IndexOf(contractName));

                var op = operations.FirstOrDefault(x => x.Name == action);
                if (op == null)
                {
                    op = new OperationDataExtended
                    {
                        Name = action
                    };
                    operations.Add(op);
                }

                op.LastActivityID = data.ActivityID;
            }
            if (data.EventName == "MessageEncoding/Stop")
            {
                var op = operations.FirstOrDefault(x => x.LastActivityID == data.ActivityID);
                if (op == null)
                {
                    return;
                }
                int size = (int)data.PayloadByName("Size");
                op.SentBytes += size;
            }
            if (data.EventName == "MessageDecoding/Start")
            {
                var op = operations.FirstOrDefault(x => x.LastActivityID == data.ActivityID);
                if (op == null)
                {
                    return;
                }
                // Remember thread ID
                pendingReceiveOps[data.ThreadID] = op;
            }
            if (data.EventName == "MessageDecoding/Stop")
            {
                // Find pending OP by thred ID
                OperationDataExtended op;
                if (!pendingReceiveOps.TryGetValue(data.ThreadID, out op))
                {
                    return;
                }
                int size = (int)data.PayloadByName("Size");
                op.ReceivedBytes += size;
            }
            if (data.EventName == "ServiceChannelCall/Stop")
            {
                // Find pending OP by thred ID
                OperationDataExtended op;
                if (!pendingReceiveOps.TryGetValue(data.ThreadID, out op))
                {
                    return;
                }

                // Find start time by thread ID
                double startTime;
                if (!opStartTimeStamps.TryGetValue(data.ThreadID, out startTime))
                {
                    return;
                }

                double duration = data.TimeStampRelativeMSec - startTime;
                op.Duration += TimeSpan.FromMilliseconds(duration);
                op.Calls++;

                Notify();
            }
        }
コード例 #27
0
        private static void ParseExtensionsLoggingEvent(TraceEvent data,
                                                        int minRequestDurationMilliseconds,
                                                        string eventArgs,
                                                        Dictionary <string, AspNetCoreRequest> aspnetCoreRequests,
                                                        Dictionary <AspNetCoreRequest, List <AspNetCoreTraceEvent> > failedRequests,
                                                        Dictionary <AspNetCoreRequestId, List <AspNetCoreTraceEvent> > requestsFullTrace,
                                                        AspNetCoreRequestEventType eventType)
        {
            var    loggerName = data.PayloadByName("LoggerName").ToString();
            string rawMessage = "";

            if (!string.IsNullOrWhiteSpace(eventArgs))
            {
                if (data.PayloadByName(eventArgs) != null)
                {
                    rawMessage = data.PayloadByName(eventArgs).ToString();
                    if (rawMessage.ToLower().Contains("StructValue[]".ToLower()))
                    {
                        rawMessage = "";
                        try
                        {
                            var args = (IDictionary <string, object>[])data.PayloadByName(eventArgs);
                            foreach (IDictionary <string, object> item in args.ToList())
                            {
                                var dict = item.ToDictionary(x => x.Key, x => x.Value);
                                rawMessage += $" {dict["Key"].ToString()}->[{dict["Value"].ToString()}]";
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                    if (rawMessage.Length > 250)
                    {
                        rawMessage = rawMessage.Substring(0, 250) + "...[REMOVED_AS_MESSAGE_TOO_LARGE]";
                    }
                    rawMessage = eventType.ToString() + ":" + rawMessage;
                }
            }
            else
            {
                rawMessage = eventType.ToString();
            }

            var shortActivityId = StartStopActivityComputer.ActivityPathString(data.ActivityID);

            foreach (var key in requestsFullTrace.Keys.ToArray())
            {
                if (shortActivityId.StartsWith(key.ShortActivityId))
                {
                    AddRawAspNetTraceToDictionary(key, shortActivityId, loggerName, rawMessage, data, requestsFullTrace);
                    break;
                }
            }

            if (CheckAspNetLogger(loggerName) && eventType == AspNetCoreRequestEventType.Start)
            {
                if (data.ActivityID != Guid.Empty)
                {
                    if (!aspnetCoreRequests.ContainsKey(shortActivityId))
                    {
                        var coreRequest = new AspNetCoreRequest
                        {
                            ShortActivityId   = shortActivityId,
                            ProcessId         = data.ProcessID,
                            ActivityId        = data.ActivityID,
                            RelatedActivityId = StartStopActivityComputer.ActivityPathString(data.RelatedActivityID)
                        };
                        var arguments = (IDictionary <string, object>[])data.PayloadByName("Arguments");

                        GetAspnetCoreRequestDetailsFromArgs(arguments.ToList(), out coreRequest.Path, out coreRequest.RequestId);
                        coreRequest.StartTimeRelativeMSec = data.TimeStampRelativeMSec;

                        if (!string.IsNullOrWhiteSpace(coreRequest.Path) && !string.IsNullOrWhiteSpace(coreRequest.RequestId))
                        {
                            aspnetCoreRequests.Add(shortActivityId, coreRequest);
                        }
                    }

                    AspNetCoreRequestId requestId = new AspNetCoreRequestId
                    {
                        ShortActivityId = shortActivityId,
                        ActivityId      = data.ActivityID
                    };
                    AddRawAspNetTraceToDictionary(requestId, shortActivityId, loggerName, rawMessage, data, requestsFullTrace);
                }
            }
            if (CheckAspNetLogger(loggerName) && eventType == AspNetCoreRequestEventType.Stop)
            {
                if (data.ActivityID != Guid.Empty)
                {
                    if (aspnetCoreRequests.TryGetValue(shortActivityId, out AspNetCoreRequest coreRequest))
                    {
                        //
                        // We are setting EndTime in 'Request finished' as well. Not
                        // sure which is the correct one right now, so doing it both.
                        //
                        coreRequest.EndTimeRelativeMSec = data.TimeStampRelativeMSec;
                        if ((coreRequest.EndTimeRelativeMSec - coreRequest.StartTimeRelativeMSec) < minRequestDurationMilliseconds)
                        {
                            var keyToRemove = requestsFullTrace.Keys.Where(x => x.ShortActivityId == coreRequest.ShortActivityId).FirstOrDefault();
                            if (keyToRemove != null)
                            {
                                requestsFullTrace.Remove(keyToRemove);
                            }
                        }
                    }
                }
            }
            if (CheckAspNetLogger(loggerName) && eventType == AspNetCoreRequestEventType.Message)
            {
                string formattedMessage = string.Empty;
                if (data.PayloadByName("FormattedMessage") != null)
                {
                    formattedMessage = data.PayloadByName("FormattedMessage").ToString();
                }
                else if (data.PayloadByName("EventName") != null)
                {
                    formattedMessage = data.PayloadByName("EventName").ToString();
                }

                if (data.ActivityID != Guid.Empty)
                {
                    if (formattedMessage.StartsWith("Request finished", StringComparison.OrdinalIgnoreCase))
                    {
                        if (aspnetCoreRequests.TryGetValue(shortActivityId, out AspNetCoreRequest coreRequest))
                        {
                            int statusCode = GetStatusCodeFromRequestFinishedMessage(formattedMessage);
                            if (statusCode > 0)
                            {
                                coreRequest.StatusCode          = statusCode;
                                coreRequest.EndTimeRelativeMSec = data.TimeStampRelativeMSec;
                            }
                            if (statusCode >= 500)
                            {
                                AspNetCoreRequestId requestId = new AspNetCoreRequestId
                                {
                                    ShortActivityId = shortActivityId,
                                    ActivityId      = data.ActivityID
                                };

                                var requestFullTraceFailedRequest = requestsFullTrace.Where(x => x.Key.ShortActivityId == coreRequest.ShortActivityId).FirstOrDefault();
                                if (requestFullTraceFailedRequest.Value != null && failedRequests.Count() < MAX_FAILED_REQUESTS_TO_TRACE)
                                {
                                    failedRequests.Add(coreRequest.Clone(), requestFullTraceFailedRequest.Value.ToArray().ToList());
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #28
0
        protected ProfilerEvent?GetProfilerEvent(TraceEvent traceEvent)
        {
            string       statement    = "";
            EventType    eventType    = EventType.None;
            EventSubType eventSubType = EventSubType.None;
            string       objectType   = string.Empty;
            int          objectId     = 0;
            int          lineNo       = 0;

            int sessionId = GetSessionId(traceEvent);

            Guid   appId    = Guid.Empty;
            string appInfo  = "";
            string tenant   = "";
            string userName = "";

            if (ContainsPayload(traceEvent, "navTenantId"))
            {
                tenant = (string)traceEvent.PayloadByName("navTenantId");
            }

            if (ContainsPayload(traceEvent, "objectExtensionAppId"))
            {
                Guid.TryParse((string)traceEvent.PayloadByName("objectExtensionAppId"), out appId);
            }

            if (ContainsPayload(traceEvent, "objectExtensionInfo"))
            {
                appInfo = (string)traceEvent.PayloadByName("objectExtensionInfo");
            }

            if (ContainsPayload(traceEvent, "userName"))
            {
                userName = (string)traceEvent.PayloadByName("userName");
            }

            switch ((int)traceEvent.ID)
            {
            case NavEvents.ALFunctionStart:
                statement    = (string)traceEvent.PayloadByName("functionName");
                objectType   = (string)traceEvent.PayloadByName("objectType");
                objectId     = (int)traceEvent.PayloadByName("objectId");
                eventType    = EventType.StartMethod;
                eventSubType = EventSubType.AlEvent;
                break;

            case NavEvents.ALFunctionStop:
                statement    = (string)traceEvent.PayloadByName("functionName");
                objectType   = (string)traceEvent.PayloadByName("objectType");
                objectId     = (int)traceEvent.PayloadByName("objectId");
                eventType    = EventType.StopMethod;
                eventSubType = EventSubType.AlEvent;
                break;

            case NavEvents.ALFunctionStatement:
                statement    = (string)traceEvent.PayloadByName("statement");
                objectType   = (string)traceEvent.PayloadByName("objectType");
                objectId     = (int)traceEvent.PayloadByName("objectId");
                lineNo       = (int)traceEvent.PayloadByName("lineNumber");
                eventType    = EventType.Statement;
                eventSubType = EventSubType.AlEvent;
                break;

            case NavEvents.SqlExecuteScalarStart:
                statement    = (string)traceEvent.PayloadByName("sqlStatement");
                eventType    = EventType.StartMethod;
                eventSubType = EventSubType.SqlEvent;
                break;

            case NavEvents.SqlExecuteScalarStop:
                statement    = (string)traceEvent.PayloadByName("sqlStatement");
                eventType    = EventType.StopMethod;
                eventSubType = EventSubType.SqlEvent;
                break;

            case NavEvents.SqlExecuteNonQueryStart:
                statement    = (string)traceEvent.PayloadByName("sqlStatement");
                eventType    = EventType.StartMethod;
                eventSubType = EventSubType.SqlEvent;
                break;

            case NavEvents.SqlExecuteNonQueryStop:
                statement    = (string)traceEvent.PayloadByName("sqlStatement");
                eventType    = EventType.StopMethod;
                eventSubType = EventSubType.SqlEvent;
                break;

            case NavEvents.SqlExecuteReaderStart:
                statement    = (string)traceEvent.PayloadByName("sqlStatement");
                eventType    = EventType.StartMethod;
                eventSubType = EventSubType.SqlEvent;
                break;

            case NavEvents.SqlExecuteReaderStop:
                statement    = (string)traceEvent.PayloadByName("sqlStatement");
                eventType    = EventType.StopMethod;
                eventSubType = EventSubType.SqlEvent;
                break;

            case NavEvents.SqlReadNextResultStart:
                statement    = (string)traceEvent.PayloadByName("sqlStatement");
                eventType    = EventType.StartMethod;
                eventSubType = EventSubType.SqlEvent;
                break;

            case NavEvents.SqlReadNextResultStop:
                statement    = (string)traceEvent.PayloadByName("sqlStatement");
                eventType    = EventType.StopMethod;
                eventSubType = EventSubType.SqlEvent;
                break;

            case NavEvents.SqlReadNextRowStart:
                statement    = (string)traceEvent.PayloadByName("sqlStatement");
                eventType    = EventType.StartMethod;
                eventSubType = EventSubType.SqlEvent;
                break;

            case NavEvents.SqlReadNextRowStop:
                statement    = (string)traceEvent.PayloadByName("sqlStatement");
                eventType    = EventType.StopMethod;
                eventSubType = EventSubType.SqlEvent;
                break;

            case NavEvents.SqlCommitStart:
                statement    = "SQL COMMIT";
                eventType    = EventType.StartMethod;
                eventSubType = EventSubType.SqlEvent;
                break;

            case NavEvents.SqlCommitStop:
                statement    = "SQL COMMIT";
                eventType    = EventType.StopMethod;
                eventSubType = EventSubType.SqlEvent;
                break;

            case NavEvents.CreateServiceSessionStart:
                statement    = "Open Session: " + (string)traceEvent.PayloadByName("connectionType");
                eventType    = EventType.StartMethod;
                eventSubType = EventSubType.SystemEvent;
                break;

            case NavEvents.CreateServiceSessionStop:
                statement    = "Open Session: " + (string)traceEvent.PayloadByName("connectionType");;
                eventType    = EventType.StopMethod;
                eventSubType = EventSubType.SystemEvent;
                break;

            case NavEvents.EndServiceSessionStart:
                statement    = "Close Session: " + (string)traceEvent.PayloadByName("connectionType");;
                eventType    = EventType.StartMethod;
                eventSubType = EventSubType.SystemEvent;
                break;

            case NavEvents.EndServiceSessionStop:
                statement    = "Close Session: " + (string)traceEvent.PayloadByName("connectionType");;
                eventType    = EventType.StopMethod;
                eventSubType = EventSubType.SystemEvent;
                break;

            default:
                return(null);
            }

            if (!string.IsNullOrEmpty(statement))
            {
                return(new ProfilerEvent
                {
                    SessionId = sessionId,
                    UserName = userName,
                    Tenant = tenant,
                    AppId = appId,
                    AppInfo = appInfo,
                    Type = eventType,
                    SubType = eventSubType,
                    ObjectType = objectType,
                    ObjectId = objectId,
                    LineNumber = lineNo,
                    StatementName = GetStatementFromTheCache(statement),
                    TimeStampRelativeMSec = traceEvent.TimeStampRelativeMSec
                });
            }

            return(null);
        }
コード例 #29
0
ファイル: TraceEventAdapter.cs プロジェクト: 0xCM/z0
 public static T Payload <T>(this TraceEvent e, string name)
 => (T)e.PayloadByName(name);
コード例 #30
0
        protected int GetSessionId(TraceEvent traceEvent)
        {
            int sessionId = (int)traceEvent.PayloadByName("sessionId");

            return(sessionId);
        }
コード例 #31
0
 /// <summary>
 /// Parse the ETW event and fill out the fields of the object.
 /// </summary>
 /// <remarks> CloudBuild ETW listener uses this method to "deserialize" the event from a TraceEvent object</remarks>
 public static Possible <CloudBuildEvent> TryParse(TraceEvent traceEvent)
 {
     return(TryParse(traceEvent.EventName, traceEvent.PayloadNames.Select(name => traceEvent.PayloadByName(name)).ToList()));
 }
コード例 #32
0
ファイル: WMIStart.cs プロジェクト: Alois-xx/WMIWatcher
        public WMIStart(TraceEvent @event, TraceLogEventSource realtimeSource, TraceLog log) : base(@event)
        {
            // Parts of the event are
            //[0]	"CorrelationId"	string
            //[1]	"GroupOperationId"	string
            //[2]	"OperationId"	string
            //[3]	"Operation"	string
            //[4]	"ClientMachine"	string
            //[5]	"ClientMachineFQDN"	string
            //[6]	"User"	string
            //[7]	"ClientProcessId"	string
            //[8]	"ClientProcessCreationTime"	string
            //[9]	"NamespaceName"	string
            //[10]	"IsLocal"	string
            // IWbemServices::CreateClassEnum - root\wmi : MSNT_SystemTrace
            // IWbemServices::ExecQuery - root\cimv2 : select Eventcode,Eventtype,Logfile,Message,Sourcename,TimeGenerated,user from Win32_NTLogEvent where eventtype = 1

            // throw if wrong event is tried to parse
            OperationId = (int)@event.ID switch
            {
                WMIProviderDefinitions.WMI_Activity_Start => (int)@event.PayloadByName("OperationId"),
                _ => throw new InvalidOperationException($"Event with ID {WMIProviderDefinitions.WMI_Activity_Start} expected. But got: {@event.ID}")
            };

            ClientProcessCreationTime = DateTime.FromFileTime((Int64)@event.PayloadByName("ClientProcessCreationTime"));

            ClientProcessId = (int)@event.PayloadByName("ClientProcessId");

            TraceProcess process = realtimeSource?.TraceLog.Processes.Where(p => p.ProcessID == ClientProcessId && p.ExitStatus == null).FirstOrDefault();

            // The process start time by Realtime ETW tracing is only correct when the process was started during that time. Otherwise it gets only the current day as start date
            if (process != null)
            {
                ClientProcess = $"{process.CommandLine}";
            }
            else
            {
                ClientProcess = "Unknown Process - Use ClientProcessId";
            }

            GroupOperationid = (int)@event.PayloadByName("GroupOperationId");
            IsRemoteQuery    = !(bool)@event.PayloadByName("IsLocal");

            // operation is a string which can have several values
            string operation = @event.PayloadByName("Operation").ToString();

            if (operation.IndexOf(Operation_ExecQuery) != -1)
            {
                Operation = WMIOperation.ExecQuery;
                ExtractNameSpaceAndQuery(Operation_ExecQuery, operation);
            }
            else if (operation.IndexOf(Operation_EnumerateClass) != -1)
            {
                Operation = WMIOperation.CreateEnumerator;
                ExtractNameSpaceAndQuery(Operation_EnumerateClass, operation);
            }
            else if (operation.IndexOf(Operation_EnumerateInstance) != -1)
            {
                Operation = WMIOperation.CreateEnumerator;
                ExtractNameSpaceAndQuery(Operation_EnumerateInstance, operation);
            }
            else if (operation.IndexOf(Operation_ExecMethod) != -1)
            {
                Operation = WMIOperation.ExecMethod;
                ExtractNameSpaceAndQuery(Operation_ExecMethod, operation);
            }
            else if (operation.IndexOf(Operation_ExecNotificatonQuery) != -1)
            {
                Operation = WMIOperation.NotificationQuery;
                ExtractNameSpaceAndQuery(Operation_ExecNotificatonQuery, operation);
            }
            else if (operation.IndexOf(Operation_Connect) != -1)
            {
                Operation = WMIOperation.Connect;
                Query     = "";
            }
            else
            {
                Operation = WMIOperation.Other;
                Query     = operation;
            }
        }

        void ExtractNameSpaceAndQuery(string prefixString, string operation)
        {
            string nameSpaceAndQuery = operation?.Substring(prefixString.Length + 3);
            int    firstColon        = nameSpaceAndQuery.IndexOf(':');

            if (firstColon != -1)
            {
                Query     = nameSpaceAndQuery?.Substring(firstColon + 2);
                NameSpace = nameSpaceAndQuery?.Substring(0, firstColon - 1);
            }
        }