private OrderedDictionary sourceEventParameters; // deserialized on demand. public ETWEvent(DateTime timestamp, Guid providerGuid, string providerName, ushort eventId, string eventName, byte eventVersion, EventKeywords keywords, EventLevel level, EventOpcode opcode, Guid activityID, int processID, int threadID, OrderedDictionary parameters) : this(timestamp, providerGuid, providerName, eventId, eventName, eventVersion, keywords, level, opcode, activityID, Guid.Empty, processID, threadID, parameters) { }
public void TraceMessageDataIsCorrectFormat() { const string vfsVersion = "test-vfsVersion"; const string providerName = "test-ProviderName"; const string eventName = "test-eventName"; const EventLevel level = EventLevel.Error; const EventOpcode opcode = EventOpcode.Start; const string enlistmentId = "test-enlistmentId"; const string gitCommandSessionId = "test_sessionId"; const string payload = "test-payload"; Dictionary <string, object> expectedDict = new Dictionary <string, object> { ["version"] = vfsVersion, ["providerName"] = providerName, ["eventName"] = eventName, ["eventLevel"] = (int)level, ["eventOpcode"] = (int)opcode, ["payload"] = new Dictionary <string, string> { ["enlistmentId"] = enlistmentId, ["gitCommandSessionId"] = gitCommandSessionId, ["json"] = payload, }, }; TelemetryDaemonEventListener.PipeMessage message = new TelemetryDaemonEventListener.PipeMessage { Version = vfsVersion, ProviderName = providerName, EventName = eventName, EventLevel = level, EventOpcode = opcode, Payload = new TelemetryDaemonEventListener.PipeMessage.PipeMessagePayload { EnlistmentId = enlistmentId, GitCommandSessionId = gitCommandSessionId, Json = payload }, }; string messageJson = message.ToJson(); Dictionary <string, object> actualDict = JsonConvert.DeserializeObject <Dictionary <string, object> >(messageJson); actualDict.Count.ShouldEqual(expectedDict.Count); actualDict["version"].ShouldEqual(expectedDict["version"]); actualDict["providerName"].ShouldEqual(expectedDict["providerName"]); actualDict["eventName"].ShouldEqual(expectedDict["eventName"]); actualDict["eventLevel"].ShouldEqual(expectedDict["eventLevel"]); actualDict["eventOpcode"].ShouldEqual(expectedDict["eventOpcode"]); Dictionary <string, string> expectedPayloadDict = (Dictionary <string, string>)expectedDict["payload"]; Dictionary <string, string> actualPayloadDict = JsonConvert.DeserializeObject <Dictionary <string, string> >(actualDict["payload"].ToString()); actualPayloadDict.Count.ShouldEqual(expectedPayloadDict.Count); actualPayloadDict["enlistmentId"].ShouldEqual(expectedPayloadDict["enlistmentId"]); actualPayloadDict["gitCommandSessionId"].ShouldEqual(expectedPayloadDict["gitCommandSessionId"]); actualPayloadDict["json"].ShouldEqual(expectedPayloadDict["json"]); }
/// <summary> /// Returns a string representation of an operation code. /// </summary> /// <param name="opcode">The operation code to get a name for.</param> /// <returns>Name of the operation code (or a numeric string, if standard name is not known).</returns> /// <remarks>Enum.GetName() could be used but it is using reflection and because of that it is an order of magnitude less efficient.</remarks> private static string GetOpcodeName(this EventOpcode opcode) { switch (opcode) { case EventOpcode.Info: return(nameof(EventOpcode.Info)); case EventOpcode.Start: return(nameof(EventOpcode.Start)); case EventOpcode.Stop: return(nameof(EventOpcode.Stop)); case EventOpcode.DataCollectionStart: return(nameof(EventOpcode.DataCollectionStart)); case EventOpcode.DataCollectionStop: return(nameof(EventOpcode.DataCollectionStop)); case EventOpcode.Extension: return(nameof(EventOpcode.Extension)); case EventOpcode.Reply: return(nameof(EventOpcode.Reply)); case EventOpcode.Resume: return(nameof(EventOpcode.Resume)); case EventOpcode.Suspend: return(nameof(EventOpcode.Suspend)); case EventOpcode.Send: return(nameof(EventOpcode.Send)); case EventOpcode.Receive: return(nameof(EventOpcode.Receive)); default: return(opcode.ToString()); } }
internal TraceLoggingTypeInfo( Type dataType, string name, EventLevel level, EventOpcode opcode, EventKeywords keywords, EventTags tags) { if (dataType == null) { throw new ArgumentNullException("dataType"); } if (name == null) { throw new ArgumentNullException("eventName"); } Contract.EndContractBlock(); Statics.CheckName(name); this.name = name; this.keywords = keywords; this.level = level; this.opcode = opcode; this.tags = tags; this.dataType = dataType; this.propertyValueFactory = PropertyValue.GetFactory(dataType); }
internal TraceLoggingTypeInfo( Type dataType, string name, EventLevel level, EventOpcode opcode, EventKeywords keywords, EventTags tags) { if (dataType == null) { throw new ArgumentNullException("dataType"); } if (name == null) { throw new ArgumentNullException("eventName"); } Contract.EndContractBlock(); Statics.CheckName(name); this.name = name; this.keywords = keywords; this.level = level; this.opcode = opcode; this.tags = tags; this.dataType = dataType; }
protected abstract void RecordMessageInternal( string eventName, Guid activityId, Guid parentActivityId, EventLevel level, Keywords keywords, EventOpcode opcode, string payload);
public void VerifyEvent(ClientEventId id, EventLevel level, EventKeywords keywords, EventOpcode opcode, params object[] payloadItems) { Assert.Equal(1, this.Events.Count); Assert.Equal((int)id, this.Events[0].EventId); Assert.Equal(level, this.Events[0].Level); Assert.Equal(opcode, this.Events[0].Opcode); Assert.True(this.Events[0].Keywords.HasFlag(keywords)); Assert.Equal(payloadItems, this.Events[0].Payload.ToArray()); }
protected override void RecordMessageInternal( string eventName, Guid activityId, Guid parentActivityId, EventLevel level, Keywords keywords, EventOpcode opcode, string jsonPayload) { Console.WriteLine(this.GetLogString(eventName, opcode, jsonPayload)); }
public EventDescriptor(int eventId, int?task = null, EventOpcode opcode = EventOpcode.Info, byte channel = 0, byte level = 0, long keywords = 0, byte version = 1, long activityId = 0, long relatedActivityId = 0) { EventId = eventId; Version = version; Channel = channel; Level = level; Opcode = opcode; Task = task ?? EventId; Keywords = keywords; ActivityId = activityId; RelatedActivityId = relatedActivityId; }
// Token: 0x06003466 RID: 13414 RVA: 0x000CBEE0 File Offset: 0x000CA0E0 private string GetOpcodeName(EventOpcode opcode, string eventName) { switch (opcode) { case EventOpcode.Info: return("win:Info"); case EventOpcode.Start: return("win:Start"); case EventOpcode.Stop: return("win:Stop"); case EventOpcode.DataCollectionStart: return("win:DC_Start"); case EventOpcode.DataCollectionStop: return("win:DC_Stop"); case EventOpcode.Extension: return("win:Extension"); case EventOpcode.Reply: return("win:Reply"); case EventOpcode.Resume: return("win:Resume"); case EventOpcode.Suspend: return("win:Suspend"); case EventOpcode.Send: return("win:Send"); default: if (opcode != EventOpcode.Receive) { string result; if (this.opcodeTab == null || !this.opcodeTab.TryGetValue((int)opcode, out result)) { this.ManifestError(Environment.GetResourceString("EventSource_UndefinedOpcode", new object[] { opcode, eventName }), true); result = null; } return(result); } return("win:Receive"); } }
protected override void RecordMessageInternal( string eventName, Guid activityId, Guid parentActivityId, EventLevel level, Keywords keywords, EventOpcode opcode, string jsonPayload) { if (string.IsNullOrEmpty(jsonPayload)) { return; } ConsoleOutputPayload payload = JsonConvert.DeserializeObject <ConsoleOutputPayload>(jsonPayload); if (string.IsNullOrEmpty(payload.ErrorMessage)) { return; } // It's necessary to do a lock here because this can be called in a multi-threaded // environment and we want to make sure that ForegroundColor is restored correctly. lock (consoleLock) { ConsoleColor prevColor = Console.ForegroundColor; string prefix; switch (level) { case EventLevel.Critical: case EventLevel.Error: case EventLevel.LogAlways: prefix = "Error"; Console.ForegroundColor = ConsoleColor.Red; break; case EventLevel.Warning: prefix = "Warning"; Console.ForegroundColor = ConsoleColor.Yellow; break; default: prefix = "Info"; break; } // The leading \r interacts with the spinner, which always leaves the // cursor at the end of the line, rather than the start. Console.WriteLine($"\r{prefix}: {payload.ErrorMessage}"); Console.ForegroundColor = prevColor; } }
private string GetOpcodeName(EventOpcode opcode, string eventName) { switch (opcode) { case EventOpcode.Info: return("win:Info"); case EventOpcode.Start: return("win:Start"); case EventOpcode.Stop: return("win:Stop"); case EventOpcode.DataCollectionStart: return("win:DC_Start"); case EventOpcode.DataCollectionStop: return("win:DC_Stop"); case EventOpcode.Extension: return("win:Extension"); case EventOpcode.Reply: return("win:Reply"); case EventOpcode.Resume: return("win:Resume"); case EventOpcode.Suspend: return("win:Suspend"); case EventOpcode.Send: return("win:Send"); case EventOpcode.Receive: return("win:Receive"); } string str = null; if (this.opcodeTab == null) { this.opcodeTab = new Dictionary <int, string>(); } if (!this.opcodeTab.TryGetValue((int)opcode, out str)) { this.opcodeTab[(int)opcode] = eventName; } return(eventName); }
/// <summary> /// Initializes a new instance of the <see cref="Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Schema.EventSchema"/> class with the specified values. /// </summary> /// <param name="id">The event id.</param> /// <param name="providerId">The provider GUID.</param> /// <param name="providerName">The provider name.</param> /// <param name="level">The event level.</param> /// <param name="task">The event task.</param> /// <param name="taskName">The event task name.</param> /// <param name="opcode">The event operation code.</param> /// <param name="opcodeName">The event operation code name.</param> /// <param name="keywords">The event keywords.</param> /// <param name="keywordsDescription">The event keywords description.</param> /// <param name="version">The event version.</param> /// <param name="payload">The event payload.</param> public EventSchema(int id, Guid providerId, string providerName, EventLevel level, EventTask task, string taskName, EventOpcode opcode, string opcodeName, EventKeywords keywords, string keywordsDescription, int version, IEnumerable <string> payload) { this.id = id; this.providerId = providerId; this.providerName = providerName; this.level = level; this.task = task; this.taskName = taskName; this.opcode = opcode; this.opcodeName = opcodeName; this.keywords = keywords; this.keywordsDescription = keywordsDescription; this.version = version; this.payload = payload.ToArray(); }
/// <summary> /// Initializes a new instance of the <see cref="Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Schema.EventSchema"/> class with the specified values. /// </summary> /// <param name="id">The event id.</param> /// <param name="providerId">The provider GUID.</param> /// <param name="providerName">The provider name.</param> /// <param name="level">The event level.</param> /// <param name="task">The event task.</param> /// <param name="taskName">The event task name.</param> /// <param name="opcode">The event operation code.</param> /// <param name="opcodeName">The event operation code name.</param> /// <param name="keywords">The event keywords.</param> /// <param name="keywordsDescription">The event keywords description.</param> /// <param name="version">The event version.</param> /// <param name="payload">The event payload.</param> public EventSchema(int id, Guid providerId, string providerName, EventLevel level, EventTask task, string taskName, EventOpcode opcode, string opcodeName, EventKeywords keywords, string keywordsDescription, int version, IEnumerable<string> payload) { this.id = id; this.providerId = providerId; this.providerName = providerName; this.level = level; this.task = task; this.taskName = taskName; this.opcode = opcode; this.opcodeName = opcodeName; this.keywords = keywords; this.keywordsDescription = keywordsDescription; this.version = version; this.payload = payload.ToArray(); }
/// <summary> /// Initializes a new instance of the TraceLoggingTypeInfo class, using /// the specified values for the EventName, Level, Opcode, Keywords, /// FieldName, and Traits properties. /// </summary> /// <param name="name"> /// The value for the Name property. Must not contain '\0' characters. /// Must not be null. /// </param> /// <param name="level"> /// The value for the Level property, or -1 to mark Level as unset. /// </param> /// <param name="opcode"> /// The value for the Opcode property, or -1 to mark Opcode as unset. /// </param> /// <param name="keywords"> /// The value for the Keywords property. /// </param> /// <param name="tags"> /// The value for the Tags property. /// </param> protected TraceLoggingTypeInfo( string name, EventLevel level, EventOpcode opcode, EventKeywords keywords, EventTags tags) : base( typeof(DataType), name, level, opcode, keywords, tags) { return; }
public static EventEntry Create( int eventId = 0, Guid providerId = default(Guid), string providerName = null, EventLevel level = default(EventLevel), EventTask task = default(EventTask), string taskName = null, EventOpcode opcode = default(EventOpcode), string opcodeName = null, EventKeywords keywords = default(EventKeywords), string keywordsDescription = null, int version = 0, IEnumerable<string> payloadNames = null, string formattedMessage = null, IEnumerable<object> payload = null, DateTimeOffset timestamp = default(DateTimeOffset), Guid activityId = default(Guid), Guid relatedActivityId = default(Guid), int processId = 0, int threadId = 0) { return new EventEntry( providerId, eventId, formattedMessage, new ReadOnlyCollection<object>((payload ?? Enumerable.Empty<object>()).ToList()), timestamp != default(DateTimeOffset) ? timestamp : DateTimeOffset.UtcNow, processId, threadId, activityId, relatedActivityId, new EventSchema( eventId, providerId, providerName, level, task, taskName, opcode, opcodeName, keywords, keywordsDescription, version, (payloadNames ?? Enumerable.Empty<string>()))); }
public static EventEntry Create( int eventId = 0, Guid providerId = default(Guid), string providerName = null, EventLevel level = default(EventLevel), EventTask task = default(EventTask), string taskName = null, EventOpcode opcode = default(EventOpcode), string opcodeName = null, EventKeywords keywords = default(EventKeywords), string keywordsDescription = null, int version = 0, IEnumerable <string> payloadNames = null, string formattedMessage = null, IEnumerable <object> payload = null, DateTimeOffset timestamp = default(DateTimeOffset), Guid activityId = default(Guid), Guid relatedActivityId = default(Guid), int processId = 0, int threadId = 0) { return (new EventEntry( providerId, eventId, formattedMessage, new ReadOnlyCollection <object>((payload ?? Enumerable.Empty <object>()).ToList()), timestamp != default(DateTimeOffset) ? timestamp : DateTimeOffset.UtcNow, processId, threadId, activityId, relatedActivityId, new EventSchema( eventId, providerId, providerName, level, task, taskName, opcode, opcodeName, keywords, keywordsDescription, version, (payloadNames ?? Enumerable.Empty <string>())))); }
internal TraceLoggingTypeInfo(Type dataType, string name, EventLevel level, EventOpcode opcode, EventKeywords keywords, EventTags tags) { if (dataType == (Type)null) { throw new ArgumentNullException("dataType"); } if (name == null) { throw new ArgumentNullException("eventName"); } Statics.CheckName(name); this.name = name; this.keywords = keywords; this.level = level; this.opcode = opcode; this.tags = tags; this.dataType = dataType; }
protected string GetLogString(string eventName, EventOpcode opcode, string jsonPayload) { // Make a smarter guess (than 16 characters) about initial size to reduce allocations StringBuilder message = new StringBuilder(1024); message.AppendFormat("[{0}] {1}", DateTime.Now, eventName); if (opcode != 0) { message.Append(" (" + opcode + ")"); } if (!string.IsNullOrEmpty(jsonPayload)) { message.Append(" " + jsonPayload); } return(message.ToString()); }
public TypeAnalysis(Type dataType, EventDataAttribute eventAttrib, List <Type> recursionCheck) { IEnumerable <PropertyInfo> properties = Statics.GetProperties(dataType); List <PropertyAnalysis> propertyAnalysisList = new List <PropertyAnalysis>(); foreach (PropertyInfo propInfo in properties) { if (!Statics.HasCustomAttribute(propInfo, typeof(EventIgnoreAttribute)) && propInfo.CanRead && propInfo.GetIndexParameters().Length == 0) { MethodInfo getMethod = Statics.GetGetMethod(propInfo); if (!(getMethod == (MethodInfo)null) && !getMethod.IsStatic && getMethod.IsPublic) { TraceLoggingTypeInfo typeInfoInstance = Statics.GetTypeInfoInstance(propInfo.PropertyType, recursionCheck); EventFieldAttribute customAttribute = Statics.GetCustomAttribute <EventFieldAttribute>(propInfo); string name = customAttribute == null || customAttribute.Name == null ? (Statics.ShouldOverrideFieldName(propInfo.Name) ? typeInfoInstance.Name : propInfo.Name) : customAttribute.Name; propertyAnalysisList.Add(new PropertyAnalysis(name, getMethod, typeInfoInstance, customAttribute)); } } } this.properties = propertyAnalysisList.ToArray(); foreach (PropertyAnalysis property in this.properties) { TraceLoggingTypeInfo traceLoggingTypeInfo = property.typeInfo; this.level = (EventLevel)Statics.Combine((int)traceLoggingTypeInfo.Level, (int)this.level); this.opcode = (EventOpcode)Statics.Combine((int)traceLoggingTypeInfo.Opcode, (int)this.opcode); this.keywords = this.keywords | traceLoggingTypeInfo.Keywords; this.tags = this.tags | traceLoggingTypeInfo.Tags; } if (eventAttrib != null) { this.level = (EventLevel)Statics.Combine((int)eventAttrib.Level, (int)this.level); this.opcode = (EventOpcode)Statics.Combine((int)eventAttrib.Opcode, (int)this.opcode); this.keywords = this.keywords | eventAttrib.Keywords; this.tags = this.tags | eventAttrib.Tags; this.name = eventAttrib.Name; } if (this.name != null) { return; } this.name = dataType.Name; }
private void WriteEvent(OperationTelemetry item, EventOpcode eventOpCode) { var payload = new { IKey = item.Context.InstrumentationKey, Id = item.Id, Name = item.Name, RootId = item.Context.Operation.Id }; if (item is RequestTelemetry) { this.EventSourceInternal.Write( RequestTelemetry.TelemetryName, new EventSourceOptions { Keywords = Keywords.Operations, Opcode = eventOpCode, Level = EventLevel.Informational }, payload); } else { this.EventSourceInternal.Write( OperationTelemetry.TelemetryName, new EventSourceOptions { ActivityOptions = EventActivityOptions.Recursive, Keywords = Keywords.Operations, Opcode = eventOpCode, Level = EventLevel.Informational }, payload); } }
public ETWEvent(DateTime timestamp, Guid providerGuid, string providerName, ushort eventId, string eventName, byte eventVersion, EventKeywords keywords, EventLevel level, EventOpcode opcode, Guid activityID, Guid relatedActivityID, int processID, int threadID, OrderedDictionary parameters) { this.SourceEvent = null; this.isFromSerializedData = false; this.sourceData = new EventData(); this.Timestamp = timestamp; this.ProviderID = providerGuid; this.ProviderName = providerName; this.ActivityID = activityID; this.RelatedActivityID = relatedActivityID; this.ID = eventId; this.EventName = eventName; this.Version = eventVersion; this.Level = level; this.OpCode = (byte)opcode; this.Keywords = (long)keywords; this.Parameters = parameters; this.ProcessID = processID; this.ThreadID = threadID; }
public byte[]? GenerateEventMetadata( int eventId, string eventName, EventKeywords keywords, EventLevel level, uint version, EventOpcode opcode, TraceLoggingEventTypes eventTypes) { TraceLoggingTypeInfo[] typeInfos = eventTypes.typeInfos; string[]? paramNames = eventTypes.paramNames; EventParameterInfo[] eventParams = new EventParameterInfo[typeInfos.Length]; for (int i = 0; i < typeInfos.Length; i++) { string paramName = string.Empty; if (paramNames != null) { paramName = paramNames[i]; } eventParams[i].SetInfo(paramName, typeInfos[i].DataType, typeInfos[i]); } return(GenerateMetadata(eventId, eventName, (long)keywords, (uint)level, version, opcode, eventParams)); }
private string GetOpcodeName(EventOpcode opcode, string eventName) { switch (opcode) { case EventOpcode.Info: return "win:Info"; case EventOpcode.Start: return "win:Start"; case EventOpcode.Stop: return "win:Stop"; case EventOpcode.DataCollectionStart: return "win:DC_Start"; case EventOpcode.DataCollectionStop: return "win:DC_Stop"; case EventOpcode.Extension: return "win:Extension"; case EventOpcode.Reply: return "win:Reply"; case EventOpcode.Resume: return "win:Resume"; case EventOpcode.Suspend: return "win:Suspend"; case EventOpcode.Send: return "win:Send"; case EventOpcode.Receive: return "win:Receive"; } // string ret = null; if (opcodeTab == null) opcodeTab = new Dictionary<int, string>(); if (!opcodeTab.TryGetValue((int)opcode, out ret)) opcodeTab[(int)opcode] = eventName; return eventName; }
private unsafe void WriteImpl <T>( string eventName, ref EventSourceOptions options, ref T data, Guid *pActivityId, Guid *pRelatedActivityId) { try { var eventTypes = SimpleEventTypes <T> .Instance; fixed(EventSourceOptions *pOptions = &options) { EventDescriptor descriptor; options.Opcode = options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName); var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor); if (nameInfo == null) { return; } var pinCount = eventTypes.pinCount; var scratch = stackalloc byte[eventTypes.scratchSize]; var descriptors = stackalloc EventData[eventTypes.dataCount + 3]; var pins = stackalloc GCHandle[pinCount]; fixed(byte * pMetadata0 = this.providerMetadata, pMetadata1 = nameInfo.nameMetadata, pMetadata2 = eventTypes.typeMetadata) { descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2); descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1); descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1); #if !ES_BUILD_PCL System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif EventOpcode opcode = (EventOpcode)descriptor.Opcode; Guid activityId = Guid.Empty; Guid relatedActivityId = Guid.Empty; if (pActivityId == null && pRelatedActivityId == null && ((options.ActivityOptions & EventActivityOptions.Disable) == 0)) { if (opcode == EventOpcode.Start) { m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions); } else if (opcode == EventOpcode.Stop) { m_activityTracker.OnStop(m_name, eventName, 0, ref activityId); } if (activityId != Guid.Empty) { pActivityId = &activityId; } if (relatedActivityId != Guid.Empty) { pRelatedActivityId = &relatedActivityId; } } try { DataCollector.ThreadInstance.Enable( scratch, eventTypes.scratchSize, descriptors + 3, eventTypes.dataCount, pins, pinCount); eventTypes.typeInfo.WriteData(TraceLoggingDataCollector.Instance, ref data); this.WriteEventRaw( eventName, ref descriptor, pActivityId, pRelatedActivityId, (int)(DataCollector.ThreadInstance.Finish() - descriptors), (IntPtr)descriptors); // if (m_Dispatchers != null) { var eventData = (EventPayload)(eventTypes.typeInfo.GetData(data)); WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, eventData); } } catch (Exception ex) { if (ex is EventSourceException) { throw; } else { ThrowEventSourceException(eventName, ex); } } finally { this.WriteCleanup(pins, pinCount); } } } } catch (Exception ex) { if (ex is EventSourceException) { throw; } else { ThrowEventSourceException(eventName, ex); } } }
public TraceEvent( IVariantEventWriter variantEventWriter, EventTask taskId, ushort eventId, string eventName, EventLevel level, EventOpcode opcode, EventChannel channel, EventKeywords keywords, string format, bool hasId, ProvisionalMetadataAttribute provisionalAttribute, int typeFieldIndex, EventExtendedMetadataAttribute extendedMetadataAttribute = null) { if (string.IsNullOrEmpty(eventName)) { throw new ArgumentException( StringResources.Error_EventNameNullOrEmpty, "eventName"); } // We need to apply a keyword mask to the keyword in order for it to show up // in the Windows Event Log. The mask that is applied depends on the channel // in which we want the event to show up. // // TODO: We are currently hard-coding the mask values, but this is not ideal // because we have reverse-engineered these values by looking at the header // file generated by mc.exe. The algorithm to determine these values is an // internal implementation detail of mc.exe. A better alternative would be // to get the mask value from the source file generated by mc.exe, instead // of hard-coding it as a constant here. ulong keywordMask = 0; switch (channel) { case EventChannel.Admin: keywordMask = AdminChannelKeywordMask; break; case EventChannel.Debug: keywordMask = DebugChannelKeywordMask; break; case EventChannel.Operational: keywordMask = OperationalChannelKeywordMask; break; } long keywordWithMask; unchecked { keywordWithMask = (long)((ulong)keywords | keywordMask | TestKeyword); } // We ignore the opcode field for now. Manifest generation does the same. this.descriptor = new GenericEventDescriptor( eventId, version, (byte)channel, (byte)level, 0, (int)taskId, keywordWithMask); this.eventName = eventName; this.taskId = taskId; this.level = level; this.filterStates = new bool[(int)TraceSinkType.Max]; this.samplingRatio = 0; this.hasId = hasId; this.typeFieldIndex = typeFieldIndex; this.format = format; this.taskName = typeof(FabricEvents.Tasks).GetFields().Single(f => (EventTask)f.GetRawConstantValue() == taskId).Name; this.variantEventWriter = variantEventWriter; // By default, provisional feature is disabled during object initialization. This needs to be enabled // by calling the Update function. this.isProvisionalFeatureEnabled = false; this.provisionalData = provisionalAttribute; if (this.provisionalData != null) { this.isProvisionalEvent = true; this.provisionalCache = AgeBasedCache <VariantId, Variant[]> .DefaultInstance; this.PopulatePositions(); } for (TraceSinkType sink = 0; sink < TraceSinkType.Max; sink++) { var status = TraceConfig.GetEventEnabledStatus(sink, this.level, this.taskId, this.eventName); var sampling = TraceConfig.GetEventSamplingRatio(sink, this.level, this.taskId, this.eventName); this.UpdateProvisionalFeatureStatus(sink, TraceConfig.GetEventProvisionalFeatureStatus(sink)); this.UpdateSinkEnabledStatus(sink, status); this.UpdateSinkSamplingRatio(sink, sampling); } #if DotNetCoreClrLinux // TODO - Following code will be removed once fully transitioned to structured traces in Linux this.linuxStructuredTracesEnabled = TraceConfig.GetLinuxStructuredTracesEnabled(); TraceConfig.OnLinuxStructuredTracesEnabledUpdate += this.UpdateLinuxStructuredTracesEnabled; #endif this.ExtendedMetadata = extendedMetadataAttribute; }
static void addBody(List<GCHandle> args, LogEventInfo data, EventOpcode opcode) { switch (opcode) { case Opcodes.Exception: addException(args, data); return; case Opcodes.Stack: addStack(args, data); return; default: return; } }
private string GetOpcodeName(EventOpcode opcode, string eventName) { switch (opcode) { case EventOpcode.Info: return "win:Info"; case EventOpcode.Start: return "win:Start"; case EventOpcode.Stop: return "win:Stop"; case EventOpcode.DataCollectionStart: return "win:DC_Start"; case EventOpcode.DataCollectionStop: return "win:DC_Stop"; case EventOpcode.Extension: return "win:Extension"; case EventOpcode.Reply: return "win:Reply"; case EventOpcode.Resume: return "win:Resume"; case EventOpcode.Suspend: return "win:Suspend"; case EventOpcode.Send: return "win:Send"; case EventOpcode.Receive: return "win:Receive"; } string ret; if (opcodeTab == null || !opcodeTab.TryGetValue((int)opcode, out ret)) throw new ArgumentException(Environment.GetResourceString("EventSource_UndefinedOpcode", opcode, eventName)); return ret; }
static int getId(LogEventInfo data, EventOpcode opcode) { var level = (int)levels[data.Level]; var code = (int)opcode; return level + code; }
internal unsafe byte[]? GenerateMetadata( int eventId, string eventName, long keywords, uint level, uint version, EventOpcode opcode, EventParameterInfo[] parameters) { byte[]? metadata = null; bool hasV2ParameterTypes = false; try { // eventID : 4 bytes // eventName : (eventName.Length + 1) * 2 bytes // keywords : 8 bytes // eventVersion : 4 bytes // level : 4 bytes // parameterCount : 4 bytes uint v1MetadataLength = 24 + ((uint)eventName.Length + 1) * 2; uint v2MetadataLength = 0; uint defaultV1MetadataLength = v1MetadataLength; // Check for an empty payload. // Write<T> calls with no arguments by convention have a parameter of // type NullTypeInfo which is serialized as nothing. if ((parameters.Length == 1) && (parameters[0].ParameterType == typeof(EmptyStruct))) { parameters = Array.Empty <EventParameterInfo>(); } // Increase the metadataLength for parameters. foreach (EventParameterInfo parameter in parameters) { uint pMetadataLength; if (!parameter.GetMetadataLength(out pMetadataLength)) { // The call above may return false which means it is an unsupported type for V1. // If that is the case we use the v2 blob for metadata instead hasV2ParameterTypes = true; break; } v1MetadataLength += (uint)pMetadataLength; } if (hasV2ParameterTypes) { v1MetadataLength = defaultV1MetadataLength; // V2 length is the parameter count (4 bytes) plus the size of the params v2MetadataLength = 4; foreach (EventParameterInfo parameter in parameters) { uint pMetadataLength; if (!parameter.GetMetadataLengthV2(out pMetadataLength)) { // We ran in to an unsupported type, return empty event metadata parameters = Array.Empty <EventParameterInfo>(); v1MetadataLength = defaultV1MetadataLength; v2MetadataLength = 0; hasV2ParameterTypes = false; break; } v2MetadataLength += (uint)pMetadataLength; } } // Optional opcode length needs 1 byte for the opcode + 5 bytes for the tag (4 bytes size, 1 byte kind) uint opcodeMetadataLength = opcode == EventOpcode.Info ? 0u : 6u; // Optional V2 metadata needs the size of the params + 5 bytes for the tag (4 bytes size, 1 byte kind) uint v2MetadataPayloadLength = v2MetadataLength == 0 ? 0 : v2MetadataLength + 5; uint totalV2MetadataLength = v2MetadataPayloadLength + opcodeMetadataLength; uint totalMetadataLength = v1MetadataLength + totalV2MetadataLength; metadata = new byte[totalMetadataLength]; // Write metadata: metadataHeaderLength, eventID, eventName, keywords, eventVersion, level, // parameterCount, param1..., optional extended metadata fixed(byte *pMetadata = metadata) { uint offset = 0; WriteToBuffer(pMetadata, totalMetadataLength, ref offset, (uint)eventId); fixed(char *pEventName = eventName) { WriteToBuffer(pMetadata, totalMetadataLength, ref offset, (byte *)pEventName, ((uint)eventName.Length + 1) * 2); } WriteToBuffer(pMetadata, totalMetadataLength, ref offset, keywords); WriteToBuffer(pMetadata, totalMetadataLength, ref offset, version); WriteToBuffer(pMetadata, totalMetadataLength, ref offset, level); if (hasV2ParameterTypes) { // If we have unsupported types, the V1 metadata must be empty. Write 0 count of params. WriteToBuffer(pMetadata, totalMetadataLength, ref offset, 0); } else { // Without unsupported V1 types we can write all the params now. WriteToBuffer(pMetadata, totalMetadataLength, ref offset, (uint)parameters.Length); foreach (var parameter in parameters) { if (!parameter.GenerateMetadata(pMetadata, ref offset, totalMetadataLength)) { // If we fail to generate metadata for any parameter, we should return the "default" metadata without any parameters return(GenerateMetadata(eventId, eventName, keywords, level, version, opcode, Array.Empty <EventParameterInfo>())); } } } Debug.Assert(offset == v1MetadataLength); if (opcode != EventOpcode.Info) { // Size of opcode WriteToBuffer(pMetadata, totalMetadataLength, ref offset, 1); WriteToBuffer(pMetadata, totalMetadataLength, ref offset, (byte)MetadataTag.Opcode); WriteToBuffer(pMetadata, totalMetadataLength, ref offset, (byte)opcode); } if (hasV2ParameterTypes) { // Write the V2 supported metadata now // Starting with the size of the V2 payload WriteToBuffer(pMetadata, totalMetadataLength, ref offset, v2MetadataLength); // Now the tag to identify it as a V2 parameter payload WriteToBuffer(pMetadata, totalMetadataLength, ref offset, (byte)MetadataTag.ParameterPayload); // Then the count of parameters WriteToBuffer(pMetadata, totalMetadataLength, ref offset, (uint)parameters.Length); // Finally the parameters themselves foreach (var parameter in parameters) { if (!parameter.GenerateMetadataV2(pMetadata, ref offset, totalMetadataLength)) { // If we fail to generate metadata for any parameter, we should return the "default" metadata without any parameters return(GenerateMetadata(eventId, eventName, keywords, level, version, opcode, Array.Empty <EventParameterInfo>())); } } } Debug.Assert(totalMetadataLength == offset); } } catch { // If a failure occurs during metadata generation, make sure that we don't return // malformed metadata. Instead, return a null metadata blob. // Consumers can either build in knowledge of the event or skip it entirely. metadata = null; } return(metadata); }
public void GetProviderNames_AssertProperties() { const string Prefix = "win:"; var standardOpcodeNames = new List <string>(Enum.GetNames(typeof(StandardEventOpcode))).Select(x => Prefix + x).ToList(); using (var session = new EventLogSession()) { Assert.NotEmpty(session.GetProviderNames()); foreach (string providerName in session.GetProviderNames()) { try { using (var providerMetadata = new ProviderMetadata(providerName)) { foreach (var keyword in providerMetadata.Keywords) { Assert.NotEmpty(keyword.Name); } foreach (var logLink in providerMetadata.LogLinks) { Assert.NotEmpty(logLink.LogName); } foreach (var opcode in providerMetadata.Opcodes) { if (opcode != null && standardOpcodeNames.Contains(opcode.Name)) { Assert.Contains((((StandardEventOpcode)(opcode.Value)).ToString()), opcode.Name); } } foreach (var eventMetadata in providerMetadata.Events) { EventLogLink logLink = eventMetadata.LogLink; if (logLink != null) { if (logLink.DisplayName != null && logLink.DisplayName.Equals("System")) { Assert.Equal("System", logLink.LogName); Assert.True(logLink.IsImported); } } EventLevel eventLevel = eventMetadata.Level; if (eventLevel != null) { if (eventLevel.Name != null) { // https://github.com/Microsoft/perfview/blob/d4b044abdfb4c8e40a344ca05383e04b5b6dc13a/src/related/EventRegister/winmeta.xml#L39 if (eventLevel.Name.StartsWith(Prefix) && !eventLevel.Name.Contains("ReservedLevel")) { Assert.True(System.Enum.IsDefined(typeof(StandardEventLevel), eventLevel.Value)); Assert.Contains(eventLevel.Name.Substring(4), Enum.GetNames(typeof(StandardEventLevel))); } } } EventOpcode opcode = eventMetadata.Opcode; if (opcode != null) { if (opcode.Name != null && opcode.DisplayName != null && opcode.DisplayName.ToLower().Equals("apprun")) { Assert.Contains(opcode.DisplayName.ToLower(), opcode.Name.ToLower()); } } EventTask task = eventMetadata.Task; if (task != null) { Assert.NotEqual(task, eventMetadata.Task); Assert.Equal(task.DisplayName, eventMetadata.Task.DisplayName); Assert.Equal(task.Name, eventMetadata.Task.Name); Assert.Equal(task.Value, eventMetadata.Task.Value); } IEnumerable <EventKeyword> keywords = eventMetadata.Keywords; if (eventMetadata.Keywords != null) { foreach (var keyword in eventMetadata.Keywords) { if (keyword.Name != null && keyword.Name.StartsWith(Prefix)) { Assert.True(System.Enum.IsDefined(typeof(StandardEventKeywords), keyword.Value)); } } } Assert.NotNull(eventMetadata.Template); } } } catch (EventLogException) { continue; } } } }
private void WriteEvent(string eventName, EventLevel level, Keywords keywords, EventMetadata metadata, EventOpcode opcode) { string jsonPayload = metadata != null?JsonConvert.SerializeObject(metadata) : null; foreach (InProcEventListener listener in this.listeners) { listener.RecordMessage(eventName, this.activityId, this.parentActivityId, level, keywords, opcode, jsonPayload); } }
public TypeAnalysis( Type dataType, EventDataAttribute eventAttrib, List<Type> recursionCheck) { var propertyInfos = Statics.GetProperties(dataType); var propertyList = new List<PropertyAnalysis>(); foreach (var propertyInfo in propertyInfos) { if (Statics.HasCustomAttribute(propertyInfo, typeof(EventIgnoreAttribute))) { continue; } if (!propertyInfo.CanRead || propertyInfo.GetIndexParameters().Length != 0) { continue; } MethodInfo getterInfo = Statics.GetGetMethod(propertyInfo); if (getterInfo == null) { continue; } if (getterInfo.IsStatic || !getterInfo.IsPublic) { continue; } var propertyType = propertyInfo.PropertyType; var propertyTypeInfo = Statics.GetTypeInfoInstance(propertyType, recursionCheck); var fieldAttribute = Statics.GetCustomAttribute<EventFieldAttribute>(propertyInfo); string propertyName = fieldAttribute != null && fieldAttribute.Name != null ? fieldAttribute.Name : Statics.ShouldOverrideFieldName(propertyInfo.Name) ? propertyTypeInfo.Name : propertyInfo.Name; propertyList.Add(new PropertyAnalysis( propertyName, getterInfo, propertyTypeInfo, fieldAttribute)); } this.properties = propertyList.ToArray(); foreach (var property in this.properties) { var typeInfo = property.typeInfo; this.level = (EventLevel)Statics.Combine((int)typeInfo.Level, (int)this.level); this.opcode = (EventOpcode)Statics.Combine((int)typeInfo.Opcode, (int)this.opcode); this.keywords |= typeInfo.Keywords; this.tags |= typeInfo.Tags; } if (eventAttrib != null) { this.level = (EventLevel)Statics.Combine((int)eventAttrib.Level, (int)this.level); this.opcode = (EventOpcode)Statics.Combine((int)eventAttrib.Opcode, (int)this.opcode); this.keywords |= eventAttrib.Keywords; this.tags |= eventAttrib.Tags; this.name = eventAttrib.Name; } if (this.name == null) { this.name = dataType.Name; } }
private void WriteEvent(string eventName, EventLevel level, Keywords keywords, EventMetadata metadata, EventOpcode opcode) { string jsonPayload = metadata != null?JsonConvert.SerializeObject(metadata) : null; if (this.isDisposed) { throw new ObjectDisposedException(nameof(JsonTracer)); } var message = new TraceEventMessage { EventName = eventName, ActivityId = this.activityId, ParentActivityId = this.parentActivityId, Level = level, Keywords = keywords, Opcode = opcode, Payload = jsonPayload }; // Iterating over the bag is thread-safe as the enumerator returned here // is of a snapshot of the bag. foreach (EventListener listener in this.listeners) { listener.RecordMessage(message); } }
private void WriteEvent(string eventName, EventLevel level, Keywords keywords, EventMetadata metadata, EventOpcode opcode) { string jsonPayload = metadata != null?JsonConvert.SerializeObject(metadata) : null; if (this.disposed) { Console.WriteLine("Writing to disposed tracer"); Console.WriteLine(jsonPayload); throw new ObjectDisposedException(nameof(JsonTracer)); } var message = new TraceEventMessage { EventName = eventName, ActivityId = this.activityId, ParentActivityId = this.parentActivityId, Level = level, Keywords = keywords, Opcode = opcode, Payload = jsonPayload }; foreach (EventListener listener in this.listeners) { string errorMessage; bool? success = listener.TryRecordMessage(message, out errorMessage); // Try to mark success or failure for this listener only if it was enabled for this message type if (success.HasValue) { if (success == true) { this.MarkAndLogListenerRecovery(listener); } else { this.MarkAndLogListenerFailure(listener, errorMessage); } } } }
private unsafe void WriteImpl( string eventName, ref EventSourceOptions options, object data, Guid *pActivityId, Guid *pRelatedActivityId, TraceLoggingEventTypes eventTypes) { try { fixed(EventSourceOptions *pOptions = &options) { EventDescriptor descriptor; options.Opcode = options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName); var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor); if (nameInfo == null) { return; } #if FEATURE_PERFTRACING IntPtr eventHandle = nameInfo.GetOrCreateEventHandle(m_eventPipeProvider, m_eventHandleMap, descriptor, eventTypes); Debug.Assert(eventHandle != IntPtr.Zero); #else IntPtr eventHandle = IntPtr.Zero; #endif #if FEATURE_MANAGED_ETW var pinCount = eventTypes.pinCount; var scratch = stackalloc byte[eventTypes.scratchSize]; var descriptors = stackalloc EventData[eventTypes.dataCount + 3]; for (int i = 0; i < eventTypes.dataCount + 3; i++) { descriptors[i] = default; } var pins = stackalloc GCHandle[pinCount]; for (int i = 0; i < pinCount; i++) pins[i] = default; fixed(byte * pMetadata0 = this.providerMetadata, pMetadata1 = nameInfo.nameMetadata, pMetadata2 = eventTypes.typeMetadata) { descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2); descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1); descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1); #endif // FEATURE_MANAGED_ETW #if (!ES_BUILD_PCL && !ES_BUILD_PN) System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif EventOpcode opcode = (EventOpcode)descriptor.Opcode; Guid activityId = Guid.Empty; Guid relatedActivityId = Guid.Empty; if (pActivityId == null && pRelatedActivityId == null && ((options.ActivityOptions & EventActivityOptions.Disable) == 0)) { if (opcode == EventOpcode.Start) { m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions); } else if (opcode == EventOpcode.Stop) { m_activityTracker.OnStop(m_name, eventName, 0, ref activityId); } if (activityId != Guid.Empty) { pActivityId = &activityId; } if (relatedActivityId != Guid.Empty) { pRelatedActivityId = &relatedActivityId; } } try { #if FEATURE_MANAGED_ETW DataCollector.ThreadInstance.Enable( scratch, eventTypes.scratchSize, descriptors + 3, eventTypes.dataCount, pins, pinCount); var info = eventTypes.typeInfos[0]; info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(data)); this.WriteEventRaw( eventName, ref descriptor, eventHandle, pActivityId, pRelatedActivityId, (int)(DataCollector.ThreadInstance.Finish() - descriptors), (IntPtr)descriptors); #endif // FEATURE_MANAGED_ETW // TODO enable filtering for listeners. if (m_Dispatchers != null) { var eventData = (EventPayload)(eventTypes.typeInfos[0].GetData(data)); WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, pRelatedActivityId, eventData); } } catch (Exception ex) { if (ex is EventSourceException) { throw; } else { ThrowEventSourceException(eventName, ex); } } #if FEATURE_MANAGED_ETW finally { this.WriteCleanup(pins, pinCount); } } #endif // FEATURE_MANAGED_ETW } } catch (Exception ex) { if (ex is EventSourceException) { throw; } else { ThrowEventSourceException(eventName, ex); } } }
private void WriteEvent(string eventName, EventLevel level, Keywords keywords, EventMetadata metadata, EventOpcode opcode) { string jsonPayload = metadata != null ? JsonConvert.SerializeObject(metadata) : null; if (this.disposed) { Console.WriteLine("Writing to disposed tracer"); Console.WriteLine(jsonPayload); throw new ObjectDisposedException(nameof(JsonTracer)); } foreach (InProcEventListener listener in this.listeners) { listener.RecordMessage(eventName, this.activityId, this.parentActivityId, level, keywords, opcode, jsonPayload); } }
public TypeAnalysis( Type dataType, EventDataAttribute eventAttrib, List <Type> recursionCheck) { var propertyInfos = Statics.GetProperties(dataType); var propertyList = new List <PropertyAnalysis>(); foreach (var propertyInfo in propertyInfos) { if (Statics.HasCustomAttribute(propertyInfo, typeof(EventIgnoreAttribute))) { continue; } if (!propertyInfo.CanRead || propertyInfo.GetIndexParameters().Length != 0) { continue; } MethodInfo getterInfo = Statics.GetGetMethod(propertyInfo); if (getterInfo == null) { continue; } if (getterInfo.IsStatic || !getterInfo.IsPublic) { continue; } var propertyType = propertyInfo.PropertyType; var propertyTypeInfo = TraceLoggingTypeInfo.GetInstance(propertyType, recursionCheck); var fieldAttribute = Statics.GetCustomAttribute <EventFieldAttribute>(propertyInfo); string propertyName = fieldAttribute != null && fieldAttribute.Name != null ? fieldAttribute.Name : Statics.ShouldOverrideFieldName(propertyInfo.Name) ? propertyTypeInfo.Name : propertyInfo.Name; propertyList.Add(new PropertyAnalysis( propertyName, propertyInfo, propertyTypeInfo, fieldAttribute)); } this.properties = propertyList.ToArray(); foreach (var property in this.properties) { var typeInfo = property.typeInfo; this.level = (EventLevel)Statics.Combine((int)typeInfo.Level, (int)this.level); this.opcode = (EventOpcode)Statics.Combine((int)typeInfo.Opcode, (int)this.opcode); this.keywords |= typeInfo.Keywords; this.tags |= typeInfo.Tags; } if (eventAttrib != null) { this.level = (EventLevel)Statics.Combine((int)eventAttrib.Level, (int)this.level); this.opcode = (EventOpcode)Statics.Combine((int)eventAttrib.Opcode, (int)this.opcode); this.keywords |= eventAttrib.Keywords; this.tags |= eventAttrib.Tags; this.name = eventAttrib.Name; } if (this.name == null) { this.name = dataType.Name; } }
public void RecordMessage(string eventName, Guid activityId, Guid parentActivityId, EventLevel level, Keywords keywords, EventOpcode opcode, string jsonPayload) { if (!this.IsEnabled(level, keywords)) { return; } this.RecordMessageInternal(eventName, activityId, parentActivityId, level, keywords, opcode, jsonPayload); }