internal static void EnableProvider( TraceEventSession session, Guid providerId, EventLevel level, EventKeywords matchAnyKeyword, IEnumerable<KeyValuePair<string, string>> arguments, IEnumerable<string> processNamesToFilter, bool sendManifest = true) { // Make explicit the invocation for requesting the manifest from the EventSource (Provider). var argumentsDictionary = arguments.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); if (sendManifest) { argumentsDictionary["Command"] = "SendManifest"; } var options = new TraceEventProviderOptions { Arguments = argumentsDictionary, ProcessNameFilter = processNamesToFilter.ToArray() }; session.EnableProvider(providerId, (TraceEventLevel)level, (ulong)matchAnyKeyword, options); }
/// <summary> /// Initializes a new instance of the <see cref="EventSourceSettings" /> class. /// </summary> /// <param name="name">The friendly event source name.</param> /// <param name="eventSourceId">The event source id.</param> /// <param name="level">The level.</param> /// <param name="matchAnyKeyword">The match any keyword.</param> /// <param name="arguments">The arguments for the event source.</param> /// <param name="processNameFilters">The the process filters.</param> /// <exception cref="ConfigurationException">A validation exception.</exception> public EventSourceSettings( string name = null, Guid? eventSourceId = null, EventLevel level = EventLevel.LogAlways, EventKeywords matchAnyKeyword = Keywords.All, IEnumerable<KeyValuePair<string, string>> arguments = null, IEnumerable<string> processNameFilters = null) { // If no Id, Name should not be optional so we may derive an Id from it. if (!eventSourceId.HasValue || eventSourceId == Guid.Empty) { if (string.IsNullOrWhiteSpace(name)) { throw new ConfigurationException(Properties.Resources.MissingEventSourceNameAndId); } eventSourceId = TraceEventProviders.GetEventSourceGuidFromName(name); } else if (!string.IsNullOrWhiteSpace(name)) { // throw and both name & Id specified throw new ConfigurationException(Properties.Resources.EventSourceAmbiguityError); } this.EventSourceId = eventSourceId.Value; this.Name = name ?? eventSourceId.ToString(); // Set a not null value for later use this.Level = level; this.MatchAnyKeyword = matchAnyKeyword; this.Arguments = arguments ?? Enumerable.Empty<KeyValuePair<string, string>>(); this.ProcessNamesToFilter = processNameFilters ?? Enumerable.Empty<string>(); }
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; }
internal static void EnableProvider(TraceEventSession session, Guid providerId, EventLevel level, EventKeywords matchAnyKeyword, bool sendManifest = true) { // Make explicit the invocation for requesting the manifest from the EventSource (Provider). var values = sendManifest ? new Dictionary<string, string>() { { "Command", "SendManifest" } } : null; session.EnableProvider(providerId, (TraceEventLevel)level, (ulong)matchAnyKeyword, 0, TraceEventOptions.None, values); }
public void WriteMessage(string eventMessage, EventLevel level, EventKeywords keywords) { #if ETW_SUPPORTED if(m_provider != null) m_provider.WriteMessageEvent(eventMessage, (byte)level, (long)keywords); #endif WriteToAllStreams(0, eventMessage); }
public bool IsEnabled(EventLevel level, EventKeywords keywords) { if (!m_providerEnabled) return false; if (m_level != 0 && m_level < level) return false; return m_matchAnyKeyword == 0 || (keywords & m_matchAnyKeyword) != 0; }
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()); }
public bool IsEnabled(EventLevel level, EventKeywords keywords) { if (!m_eventSourceEnabled) return false; if (m_level != 0 && m_level < level) return false; if (m_matchAnyKeyword != 0 && (keywords & m_matchAnyKeyword) == 0) return false; return true; }
/// <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(); }
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>()))); }
private void EnableAsNecessary(EventSource eventSource) { EventSourceConfiguration provider = this.EventSources.FirstOrDefault(p => p.ProviderName == eventSource.Name); if (provider != null) { // LIMITATION: There is a known issue where if we listen to the FrameworkEventSource, the dataflow pipeline may hang when it // tries to process the Threadpool event. The reason is the dataflow pipeline itself is using Task library for scheduling async // tasks, which then itself also fires Threadpool events on FrameworkEventSource at unexpected locations, and trigger deadlocks. // Hence, we like special case this and mask out Threadpool events. EventKeywords keywords = provider.Keywords; if (provider.ProviderName == "System.Diagnostics.Eventing.FrameworkEventSource") { // Turn off the Threadpool | ThreadTransfer keyword. Definition is at http://referencesource.microsoft.com/#mscorlib/system/diagnostics/eventing/frameworkeventsource.cs // However, if keywords was to begin with, then we need to set it to All first, which is 0xFFFFF.... if (keywords == 0) { keywords = EventKeywords.All; } keywords &= (EventKeywords) ~0x12; } this.EnableEvents(eventSource, provider.Level, keywords); } }
private unsafe void WriteMultiMerge( string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid *activityID, Guid *childActivityID, params object[] values) { if (!this.IsEnabled()) { return; } byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level : eventTypes.level; EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0 ? options.keywords : eventTypes.keywords; if (this.IsEnabled((EventLevel)level, keywords)) { WriteMultiMergeInner(eventName, ref options, eventTypes, activityID, childActivityID, values); } }
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)); }
internal TraceLoggingEventTypes( string name, EventTags tags, System.Reflection.ParameterInfo[] paramInfos) { if (name == null) { throw new ArgumentNullException(nameof(name)); } this.typeInfos = MakeArray(paramInfos); this.name = name; this.tags = tags; this.level = Statics.DefaultLevel; var collector = new TraceLoggingMetadataCollector(); for (int i = 0; i < typeInfos.Length; ++i) { var typeInfo = typeInfos[i]; this.level = Statics.Combine((int)typeInfo.Level, this.level); this.opcode = Statics.Combine((int)typeInfo.Opcode, this.opcode); this.keywords |= typeInfo.Keywords; var paramName = paramInfos[i].Name; if (Statics.ShouldOverrideFieldName(paramName)) { paramName = typeInfo.Name; } typeInfo.WriteMetadata(collector, paramName, EventFieldFormat.Default); } this.typeMetadata = collector.GetMetadata(); this.scratchSize = collector.ScratchSize; this.dataCount = collector.DataCount; this.pinCount = collector.PinCount; }
public bool IsEnabled(EventLevel level, EventKeywords keywords, EventChannel channel);
public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword, IDictionary <string, string> arguments);
/// <summary> /// Send a command to a provider (from a particular stream). The most important command is simply /// to turn a particular provider on or off. However particular providers might implement /// additional commands (like dumping particular data structures in response to a command. /// </summary> /// <param name="providerGuid">The GUID for the event provider that the command is to be sent to. /// Guid.Empty is defined to be a wildcard that means all providers. </param> /// <param name="enable">Indicates if the provider is to be turned on or off. The rest of the /// arguments are only appicable if enabled=true.</param> /// <param name="level">The level (verbosity) of the logging desired.</param> /// <param name="matchAnyKeyword">Providers define groups of events and each such group is given a /// bit in a 64 bit enumeration. This parameter indicates which groups should be truned on. Events /// have are not assigned any group are never filtered by the matchAnyKeyword value.</param> /// <param name="command">The command to be given to the provider. Typically it is Command.Update. /// Individual providers can define their own commands</param> /// <param name="commandArguments">This is a set of key-value pairs that are interpreted by the /// provider. It is a way of passing arbitrary arguments to the provider when issuing a command</param> public void SendCommand(Guid providerGuid, bool enable, EventLevel level, EventKeywords matchAnyKeyword, ControllerCommand command, IDictionary<string, string> commandArguments) { // Copy it to list so I can make the callback without holding the EventProviderStreamsLock. List<EventProviderBase> providerBases = new List<EventProviderBase>(); lock (EventProviderStreamsLock) { foreach (WeakReference providerRef in s_providers) { EventProviderBase providerBase = providerRef.Target as EventProviderBase; if (providerBase != null && (providerBase.Guid == providerGuid || providerGuid == Guid.Empty)) providerBases.Add(providerBase); } } foreach (EventProviderBase providerBase in providerBases) providerBase.SendCommand(this, enable, level, matchAnyKeyword, command, commandArguments); }
internal void SendCommand(EventListener eventListener, EventCommand command, bool enable, EventLevel level, EventKeywords matchAnyKeywords) { if (command == EventCommand.Update && enable) { lock (m_dispatchControlLock) { // Add the new subscription. This will overwrite an existing subscription for the listener if one exists. m_subscriptions[eventListener] = new EventListenerSubscription(matchAnyKeywords, level); // Commit the configuration change. CommitDispatchConfiguration(); } } else if (command == EventCommand.Update && !enable) { RemoveEventListener(eventListener); } }
public void AddSource(Guid guid, EventLevel level, EventKeywords keywords = EventKeywords.All) => AddSource(null, guid, level, keywords);
public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword, IDictionary <string, string> arguments) { throw new NotImplementedException(); }
/// <summary> /// Emits a _Faulted version of a given event that logs the result of an operation. /// The _Completed event is used by TracingProxy to signal an exception in a method call. /// </summary> /// <param name="invocationContext">The InvocationContext for this call.</param> /// <param name="beginMethod">The begin method for this interface call.</param> /// <param name="eventId">The next available event ID.</param> /// <param name="autoKeyword">The auto-keyword to use if enabled.</param> /// <returns>The MethodBuilder for the method.</returns> private MethodBuilder EmitMethodFaultedImpl(InvocationContext invocationContext, MethodInfo beginMethod, ref int eventId, EventKeywords autoKeyword) { return EmitMethodComplementImpl(invocationContext.SpecifyType(InvocationContextTypes.MethodFaulted), FaultedSuffix, typeof(Exception), beginMethod, ref eventId, autoKeyword, null); }
/// <summary> /// Emits a method to complement an interface method. The complement method will have a suffix such as _Completed, /// and will take one parameter. /// </summary> /// <param name="invocationContext">The InvocationContext for this call.</param> /// <param name="suffix">The suffix to use on the method.</param> /// <param name="parameterType">The type of the parameter of the method.</param> /// <param name="beginMethod">The begin method for this interface call.</param> /// <param name="eventId">The next available event ID.</param> /// <param name="autoKeyword">The auto-keyword to use if enabled.</param> /// <param name="faultedMethod">A faulted method to call or null if no other faulted method is available.</param> /// <returns>The MethodBuilder for the method.</returns> private MethodBuilder EmitMethodComplementImpl(InvocationContext invocationContext, string suffix, Type parameterType, MethodInfo beginMethod, ref int eventId, EventKeywords autoKeyword, MethodBuilder faultedMethod) { var interfaceMethod = invocationContext.MethodInfo; // if there is a NonEvent attribute, then no need to emit this method if (interfaceMethod.GetCustomAttribute<NonEventAttribute>() != null) return null; // if the method ends in _Completed, then don't emit another one if (interfaceMethod.Name.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) return null; var methodName = beginMethod.Name + suffix; // if the interface already has a _Completed method, don't emit a new one var parameterTypes = parameterType == typeof(void) ? Type.EmptyTypes : new Type[] { parameterType }; if (interfaceMethod.DeclaringType.GetMethod(methodName, parameterTypes) != null) return null; var targetParameterType = GetTypeSupportedByEventSource(parameterType); var targetParameters = parameterTypes.Select(t => TypeIsSupportedByEventSource(t) ? t : typeof(string)).ToList(); bool supportsContext = SupportsContext(invocationContext); if (supportsContext) targetParameters.Add(typeof(string)); var targetParameterTypes = targetParameters.ToArray(); // determine if this is a non-event or an event // if an event, but there is no event attribute, just add one to the last event id EventAttribute startEventAttribute = interfaceMethod.GetCustomAttribute<EventAttribute>() ?? new EventAttribute(eventId); EventAttribute eventAttribute = _eventAttributeProvider.CopyEventAttribute(startEventAttribute, invocationContext, eventId); eventId = Math.Max(eventId, eventAttribute.EventId + 1); if (eventAttribute.Keywords == EventKeywords.None) eventAttribute.Keywords = autoKeyword; // if we have a return type, then we need to implement two methods if (parameterTypes.Length == 1) { // emit the internal method MethodBuilder m = _typeBuilder.DefineMethod(methodName, MethodAttributes.Public, typeof(void), targetParameterTypes); m.SetCustomAttribute(EventAttributeHelper.ConvertEventAttributeToAttributeBuilder(eventAttribute)); EmitCallWriteEvent(invocationContext, m, eventAttribute, targetParameterTypes, targetParameterTypes); // emit an overloaded wrapper method that calls the method when it's enabled // note this is a non-event so EventSource doesn't try to log it MethodBuilder im = _typeBuilder.DefineMethod(methodName, MethodAttributes.Public); ProxyHelper.CopyGenericSignature(interfaceMethod, im); im.SetReturnType(parameterTypes[0]); im.SetParameters(parameterTypes); // mark the method as a non-event im.SetCustomAttribute(EventAttributeHelper.CreateNonEventAttribute()); // put the return value on the stack so we can return the value as a passthrough im.GetILGenerator().Emit(OpCodes.Ldarg_1); if (EmitIsEnabled(im, eventAttribute)) { EmitTaskCompletion(im, parameterType, faultedMethod); EmitDirectProxy(invocationContext, im, m, parameterTypes, targetParameterTypes); } return im; } else { // the method does not have a return value // so create the internal method that calls WriteEvent MethodBuilder m = _typeBuilder.DefineMethod(methodName, MethodAttributes.Public, typeof(void), targetParameterTypes); m.SetCustomAttribute(EventAttributeHelper.ConvertEventAttributeToAttributeBuilder(eventAttribute)); ProxyHelper.EmitDefaultValue(m.GetILGenerator(), m.ReturnType); if (EmitIsEnabled(m, eventAttribute)) EmitCallWriteEvent(invocationContext, m, eventAttribute, targetParameterTypes, targetParameterTypes); return m; } }
/// <summary> /// Emits a _Completed version of a given event that logs the result of an operation. /// The _Completed event is used by TracingProxy to signal the end of a method call. /// </summary> /// <param name="invocationContext">The InvocationContext for this call.</param> /// <param name="beginMethod">The begin method for this interface call.</param> /// <param name="eventId">The next available event ID.</param> /// <param name="autoKeyword">The auto-keyword to use if enabled.</param> /// <param name="faultedMethod">A faulted method to call or null if no other faulted method is available.</param> /// <returns>The MethodBuilder for the method.</returns> private MethodBuilder EmitMethodCompletedImpl(InvocationContext invocationContext, MethodInfo beginMethod, ref int eventId, EventKeywords autoKeyword, MethodBuilder faultedMethod) { return EmitMethodComplementImpl(invocationContext.SpecifyType(InvocationContextTypes.MethodCompletion), CompletedSuffix, invocationContext.MethodInfo.ReturnType, beginMethod, ref eventId, autoKeyword, faultedMethod); }
/// <summary> /// Enables events for the specified event source that has the specified verbosity level or lower, and matching keyword flags. /// </summary> /// <param name="eventListener">The event listener.</param> /// <param name="eventSourceName">The name of the event source to enable events for.</param> /// <param name="level">The level of events to enable.</param> /// <param name="matchAnyKeyword">The keyword flags necessary to enable the events.</param> /// <param name="arguments">The arguments to be matched to enable the events.</param> /// <returns> /// <see langword="false" /> if the request was deferred; otherwise, <see langword="true" />. /// </returns> /// <remarks> /// If the event source with the supplied name has already been created the request is processed immediately. Otherwise the request /// is deferred until the event source is created. /// </remarks> public static bool EnableEvents(this EventListener eventListener, string eventSourceName, EventLevel level, EventKeywords matchAnyKeyword, IDictionary<string, string> arguments) { return CastToObservableEventListener(eventListener).EnableEvents(eventSourceName, level, matchAnyKeyword, arguments); }
/// <summary> /// Enables events for the specified event source that has the specified verbosity level or lower, and matching keyword flags. /// </summary> /// <param name="eventListener">The event listener.</param> /// <param name="eventSourceName">The name of the event source to enable events for.</param> /// <param name="level">The level of events to enable.</param> /// <param name="matchAnyKeyword">The keyword flags necessary to enable the events.</param> /// <returns> /// <see langword="false" /> if the request was deferred; otherwise, <see langword="true" />. /// </returns> /// <remarks> /// If the event source with the supplied name has already been created the request is processed immediately. Otherwise the request /// is deferred until the event source is created. /// </remarks> public static bool EnableEvents(this EventListener eventListener, string eventSourceName, EventLevel level, EventKeywords matchAnyKeyword) { return CastToObservableEventListener(eventListener).EnableEvents(eventSourceName, level, matchAnyKeyword); }
private static bool IsEnabled(EventLevel level, EventKeywords keywords) { return false; }
internal void TraceEventServiceOutOfBandEvent(string sessionName, Guid providerId, EventLevel eventLevel, EventKeywords eventKeywords, string eventMessage) { if (this.IsEnabled()) { this.WriteEvent(811, sessionName, providerId, eventLevel, eventKeywords, eventMessage); } }
/// <summary> /// Emits an implementation of a given method. /// </summary> /// <param name="invocationContext">The InvocationContext for this call.</param> /// <param name="eventId">The next eventID to use.</param> /// <param name="autoKeyword">The auto-keyword to use if enabled.</param> /// <returns>The method that is implemented.</returns> private MethodBuilder EmitMethodImpl(InvocationContext invocationContext, ref int eventId, EventKeywords autoKeyword) { var interfaceMethod = invocationContext.MethodInfo; // look at the parameters on the interface var parameters = interfaceMethod.GetParameters(); var parameterTypes = parameters.Select(p => p.ParameterType).ToArray(); // some types aren't supported in event source. we will convert them to strings var targetParameters = parameterTypes.Select(t => GetTypeSupportedByEventSource(t)).ToList(); // if we are implementing an interface, then add an string context parameter bool supportsContext = SupportsContext(invocationContext); if (supportsContext) targetParameters.Add(typeof(string)); var targetParameterTypes = targetParameters.ToArray(); // calculate the method name // if there is more than one method with the given name, then append an ID to it var methodName = interfaceMethod.Name; var matchingMethods = interfaceMethod.DeclaringType.GetMethods().AsEnumerable().Where(im => String.Compare(im.Name, methodName, StringComparison.OrdinalIgnoreCase) == 0).ToArray(); if (matchingMethods.Length > 1) methodName += "_" + Array.IndexOf(matchingMethods, interfaceMethod).ToString(CultureInfo.InvariantCulture); // determine if this is a non-event or an event // if an event, but there is no event attribute, just add one to the last event id EventAttribute eventAttribute = null; if (interfaceMethod.GetCustomAttribute<NonEventAttribute>() == null) { eventAttribute = _eventAttributeProvider.GetEventAttribute(invocationContext, eventId); eventId = Math.Max(eventId, eventAttribute.EventId + 1); } // if auto-keywords are enabled, use them if (eventAttribute != null && eventAttribute.Keywords == EventKeywords.None) eventAttribute.Keywords = autoKeyword; // create the internal method that calls WriteEvent // this cannot be virtual or static, or the manifest builder will skip it // it also cannot return a value MethodBuilder m = _typeBuilder.DefineMethod(methodName, MethodAttributes.Public, typeof(void), targetParameterTypes); // copy the Event or NonEvent attribute from the interface if (eventAttribute != null) m.SetCustomAttribute(EventAttributeHelper.ConvertEventAttributeToAttributeBuilder(eventAttribute)); else m.SetCustomAttribute(EventAttributeHelper.CreateNonEventAttribute()); // add the parameter names for (int i = 0; i < parameters.Length; i++) { var parameter = parameters[i]; m.DefineParameter(i + 1, parameter.Attributes, parameter.Name); } // add the context parameter if (supportsContext) m.DefineParameter(parameters.Length + 1, ParameterAttributes.In, Context); if (interfaceMethod.IsAbstract) { // for interface methods, implement a call to write event EmitCallWriteEvent(invocationContext, m, eventAttribute, parameterTypes, targetParameterTypes); // since EventSource only accepts non-virtual methods, and we need a virtual method to implement the abstract method // we need to implement a wrapper method on the interface that calls into the base method MethodBuilder im = _typeBuilder.DefineMethod("_" + methodName, MethodAttributes.Public | MethodAttributes.Virtual); ProxyHelper.CopyMethodSignature(interfaceMethod, im); ProxyHelper.EmitDefaultValue(im.GetILGenerator(), im.ReturnType); if (EmitIsEnabled(im, eventAttribute)) EmitDirectProxy(invocationContext, im, m, parameterTypes, targetParameterTypes); // map our method to the interface implementation _typeBuilder.DefineMethodOverride(im, interfaceMethod); } else if (interfaceMethod.DeclaringType.IsSubclassOf(typeof(EventSource))) { // if we are implementing an event source, then // for non-abstract methods we just proxy the base implementation EmitDirectProxy(invocationContext, m, interfaceMethod, parameterTypes, targetParameterTypes); } else { // the base class is not an event source, so we are creating an eventsource-derived class // that just logs the event // so we need to call write event // call IsEnabled with the given event level and keywords to check whether we should log ProxyHelper.EmitDefaultValue(m.GetILGenerator(), m.ReturnType); if (EmitIsEnabled(m, eventAttribute)) EmitCallWriteEvent(invocationContext, m, eventAttribute, parameterTypes, targetParameterTypes); } return m; }
internal static void EnableProvider(TraceEventSession session, Guid providerId, EventLevel level, EventKeywords matchAnyKeyword) { session.EnableProvider( providerId, (TraceEventLevel)level, (ulong)matchAnyKeyword); }
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; } }
/// <summary>Enables events for the specified event source that has the specified verbosity level or lower, and matching keyword flags.</summary><param name="eventSource">The event source to enable events for.</param><param name="level">The level of events to enable.</param><param name="matchAnyKeyword">The keyword flags necessary to enable the events.</param> public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword) { throw new NotImplementedException(); }
/// <summary> /// Enable all events from the eventSource identified by 'eventSourceGuid' to the current dispatcher that have a /// verbosity level of 'level' or lower and have a event keyword matching any of the bits in /// 'machAnyKeyword'. /// /// This call can have the effect of REDUCING the number of events sent to the dispatcher if 'level' /// indicates a less verbose level than was previously enabled or if 'machAnyKeyword' has fewer /// keywords set than where previously set. /// /// If eventSourceGuid is Guid.Empty, then the affects all eventSources in the appdomain /// /// If eventSourceGuid is not Guid.Empty, this call has no effect on any other eventSources in the appdomain. /// /// This call never has an effect on other EventListeners. /// /// Returns 'true' if any eventSource could be found that matches 'eventSourceGuid' /// </summary> public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword) { EnableEvents(eventSource, level, matchAnyKeyword, null); }
public void AddSource(string name, EventLevel level, EventKeywords keywords = EventKeywords.All) => AddSource(name, null, level, keywords);
/// <summary> /// Enables events for the specified event source that has the specified verbosity level or lower, and matching keyword flags. /// </summary> /// <param name="eventSourceName">The name of the event source to enable events for.</param> /// <param name="level">The level of events to enable.</param> /// <param name="matchAnyKeyword">The keyword flags necessary to enable the events.</param> /// <returns> /// <see langword="false" /> if the request was deferred; otherwise, <see langword="true" />. /// </returns> /// <remarks> /// If the event source with the supplied name has already been created the request is processed immediately. Otherwise the request /// is deferred until the event source is created. /// </remarks> public bool EnableEvents(string eventSourceName, EventLevel level, EventKeywords matchAnyKeyword) { return(this.EnableEvents(eventSourceName, level, matchAnyKeyword, null)); }
internal EventListenerSubscription(EventKeywords matchAnyKeywords, EventLevel level) { MatchAnyKeywords = matchAnyKeywords; Level = level; }
private static TraceConfiguration EventPipeGetConfig(EventSource eventSource, EventKeywords keywords, string outputFile = "default.netperf") { // Setup the configuration values. uint circularBufferMB = 1024; // 1 GB uint level = 5; // Create a new instance of EventPipeConfiguration. TraceConfiguration config = new TraceConfiguration(outputFile, circularBufferMB); // Enable the provider. config.EnableProvider(eventSource.Name, (ulong)keywords, level); return(config); }
protected override void Output(EventLevel level, int id, string eventName, EventKeywords eventKeywords, string text, bool doNotTranslatePaths = false) { Console.WriteLine($"[{DateTime.Now:HH:mm:ss.ff}] {text}"); }
/// <summary> /// Helper method to setup shared context and call the desired tracking for testing. /// </summary> /// <param name="keywords">The event keywords to enable.</param> /// <param name="item">The telemetry item to track.</param> /// <param name="track">The tracking callback to execute.</param> private void DoTracking(EventKeywords keywords, ITelemetry item, Action<TelemetryClient, ITelemetry> track) { var client = new TelemetryClient(); client.InstrumentationKey = Guid.NewGuid().ToString(); using (var listener = new Microsoft.ApplicationInsights.TestFramework.TestEventListener()) { listener.EnableEvents(RichPayloadEventSource.Log.EventSourceInternal, EventLevel.Verbose, keywords); item.Context.Properties.Add("property1", "value1"); item.Context.User.Id = "testUserId"; item.Context.Operation.Id = Guid.NewGuid().ToString(); track(client, item); var actualEvent = listener.Messages.FirstOrDefault(); Assert.IsNotNull(actualEvent); Assert.AreEqual(client.InstrumentationKey, actualEvent.Payload[0]); int keysFound = 0; object[] tags = actualEvent.Payload[1] as object[]; foreach (object tagObject in tags) { Dictionary<string, object> tag = (Dictionary<string, object>)tagObject; Assert.IsNotNull(tag); string key = (string)tag["Key"]; object value = tag["Value"]; if (!string.IsNullOrWhiteSpace(key)) { if (key == "ai.user.id") { Assert.AreEqual("testUserId", value); ++keysFound; } else if (key == "ai.operation.id") { Assert.AreEqual(item.Context.Operation.Id, value); ++keysFound; } } } Assert.AreEqual(2, keysFound); Assert.IsNotNull(actualEvent.Payload[2]); } }
private static string ToHex(EventKeywords value) { return string.Format(CultureInfo.InvariantCulture, "0x{0:X}", (long)value); }
// This is the internal entry point that code:EventListeners call when wanting to send a command to a // eventSource. The logic is as follows // // * if Command == Update // * enabled, level, matchAnyKeywords are used to set a default for all events for the // curEventSource. In particular, if 'enabled' is false, 'level' and // 'matchAnyKeywords' are not used. // * OnEventCommand is invoked, which may cause calls to // code:EventSource.EnableEventForDispatcher which may cause changes in the filtering // depending on the logic in that routine. // * else (command != Update) // * Simply call OnEventCommand. The expectation is that filtering is NOT changed. // * The 'enabled' 'level', matchAnyKeyword' arguments are ignored (must be true, 0, 0). // // dispatcher == null has special meaning. It is the 'ETW' dispatcher. internal void SendCommand(EventListener listener, EventCommand command, bool enable, EventLevel level, EventKeywords matchAnyKeyword, IDictionary<string, string> commandArguments) { m_lastCommandException = null; try { InsureInitialized(); // Find the per-EventSource dispatcher cooresponding to registered dispatcher EventDispatcher eventSourceDispatcher = GetDispatcher(listener); if (eventSourceDispatcher == null && listener != null) // dispatcher == null means ETW dispatcher throw new ArgumentException(SR.EventSource_ListenerNotFound); if (commandArguments == null) commandArguments = new Dictionary<string, string>(); if (command == EventCommand.Update) { // Set it up using the 'standard' filtering bitfields for (int i = 0; i < m_eventData.Length; i++) EnableEventForDispatcher(eventSourceDispatcher, i, IsEnabledByDefault(i, enable, level, matchAnyKeyword)); command = EventCommand.Disable; if (enable) { command = EventCommand.Enable; if (!m_eventSourceEnabled) { // EventSource turned on for the first time, simply copy the bits. m_level = level; m_matchAnyKeyword = matchAnyKeyword; } else { // Already enabled, make it the most verbose of the existing and new filter if (level > m_level) m_level = level; if (matchAnyKeyword == 0) m_matchAnyKeyword = 0; else if (m_matchAnyKeyword != 0) m_matchAnyKeyword |= matchAnyKeyword; } // Send the manifest if we are writing to ETW if (eventSourceDispatcher == null) { // eventSourceDispatcher == null means this is the ETW manifest // If we are not completely initalized we can't send the manifest because WriteEvent // will fail (handle was not returned from OS API). We will try again after the // constuctor completes. if (!m_ETWManifestSent && m_completelyInited) { m_ETWManifestSent = true; SendManifest(m_rawManifest); } } } this.OnEventCommand(new EventCommandEventArgs(command, commandArguments, this, eventSourceDispatcher)); if (enable) { m_eventSourceEnabled = true; } else { // If we are disabling, maybe we can turn so 'quick checks' to filter // quickly. These are all just optimizations (since later checks will still filter) // reset the 'manifestSent' bit for the listener. if (eventSourceDispatcher == null) m_ETWManifestSent = false; // Null dispatcher means ETW dispatcher. // There is a good chance EnabledForAnyListener are not as accurate as // they could be, go ahead and get a better estimate. for (int i = 0; i < m_eventData.Length; i++) { m_eventData[i].EnabledForAnyListener = false; for (EventDispatcher dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) { if (dispatcher.m_EventEnabled[i]) { m_eventData[i].EnabledForAnyListener = true; break; } } } // If no events are enabled, disable the global enabled bit. if (!AnyEventEnabled()) { m_level = 0; m_matchAnyKeyword = 0; m_eventSourceEnabled = false; } } } else { if (command == EventCommand.SendManifest) SendManifest(m_rawManifest); // These are not used for non-update commands and thus should always be 'default' values Contract.Assert(enable == true); Contract.Assert(m_level == EventLevel.LogAlways); Contract.Assert(m_matchAnyKeyword == EventKeywords.None); this.OnEventCommand(new EventCommandEventArgs(command, commandArguments, null, null)); } } catch (Exception e) { // Remember any exception and rethrow. m_lastCommandException = e; throw; } }
public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword);
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; }
public bool IsEnabled(EventLevel level, EventKeywords keywords);
private bool IsEnabled(EventLevel level, EventKeywords keywords) { return(m_eventSource.IsEnabled(level, keywords)); }
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; } }
internal void SendCommand(EventProviderDataStream outputStream, bool enable, EventLevel level, EventKeywords matchAnyKeyword, ControllerCommand command, IDictionary<string, string> commandArguments) { InsureInitialized(); if (m_OutputStreams != null && m_eventCallbackArgs == null) m_eventCallbackArgs = new EventWrittenEventArgs(this); m_providerEnabled = enable; m_level = level; m_matchAnyKeyword = matchAnyKeyword; // Find the per-Provider stream cooresponding to registered outputStream EventProviderDataStream providerOutputStream = m_OutputStreams; if (providerOutputStream != null) { for (; ; ) { if (providerOutputStream == null) throw new ArgumentException("outputStream not found"); if (providerOutputStream.m_MasterStream == outputStream) break; providerOutputStream = providerOutputStream.m_Next; } } if (enable) { // Send the manifest if the stream once per stream if (providerOutputStream != null) { if (!providerOutputStream.m_ManifestSent) { providerOutputStream.m_ManifestSent = true; SendManifest(m_rawManifest, providerOutputStream); } } else { // providerOutputStream == null means this is the ETW manifest // If we are not completely initalized we can't send the manifest because WriteEvent // will fail (handle was not returned from OS API). We will try again after the // constuctor completes. if (!m_ETWManifestSent && m_completelyInited) { m_ETWManifestSent = true; SendManifest(m_rawManifest, providerOutputStream); } } } else { // if (providerOutputStream != null) providerOutputStream.m_ManifestSent = false; else m_ETWManifestSent = false; } // Set it up using the 'standard' filtering bitfields for (int i = 0; i < m_eventData.Length; i++) SetEnabled(providerOutputStream, i, IsEnabledDefault(i, level, matchAnyKeyword)); if (commandArguments == null) commandArguments = new Dictionary<string, string>(); // Allow subclasses to fiddle with it from there. OnControllerCommand(providerOutputStream, command, commandArguments); }
/// <summary> /// Enable all events from the eventSource identified by 'eventSource' to the current dispatcher that have a /// verbosity level of 'level' or lower and have a event keyword matching any of the bits in /// 'machAnyKeyword' as well as any (curEventSource specific) effect passing addingional 'key-value' arguments /// 'arguments' might have. /// /// This call can have the effect of REDUCING the number of events sent to the dispatcher if 'level' /// indicates a less verbose level than was previously enabled or if 'machAnyKeyword' has fewer /// keywords set than where previously set. /// /// This call never has an effect on other EventListeners. /// </summary> public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword, IDictionary<string, string> arguments) { if (eventSource == null) { throw new ArgumentNullException(nameof(eventSource)); } Contract.EndContractBlock(); eventSource.SendCommand(this, EventCommand.Update, true, level, matchAnyKeyword, arguments); }
/// <summary> /// Observe In-Process EventSource events. It's no across ETW. /// </summary> public static IObservable <EventWrittenEventArgs> FromEventSource(EventSource eventSource, EventLevel level = EventLevel.Verbose, EventKeywords matchAnyKeyword = EventKeywords.None, IDictionary <string, string> arguments = null) { if (eventSource == null) { throw new ArgumentNullException("eventSource"); } var listener = new SystemEventSourceListener(); listener.EnableEvents(eventSource, level, matchAnyKeyword, arguments); return(listener.Finally(() => listener.DisableEvents(eventSource))); }
/// <summary> /// Returns true if 'eventNum' is enabled if you only consider the level and matchAnyKeyword filters. /// It is possible that eventSources turn off the event based on additional filtering criteria. /// </summary> private bool IsEnabledByDefault(int eventNum, bool enable, EventLevel currentLevel, EventKeywords currentMatchAnyKeyword) { if (!enable) return false; EventLevel eventLevel = (EventLevel)m_eventData[eventNum].Descriptor.Level; EventKeywords eventKeywords = (EventKeywords)m_eventData[eventNum].Descriptor.Keyword; if ((eventLevel <= currentLevel) || (currentLevel == 0)) { if ((eventKeywords == 0) || ((eventKeywords & currentMatchAnyKeyword) != 0)) return true; } return false; }
/// <summary> /// Observe In-Process EventSource events. It's no across ETW. /// </summary> public static IObservable <EventWrittenEventArgs> FromEventSource(string eventSourceName, EventLevel level = EventLevel.Verbose, EventKeywords matchAnyKeyword = EventKeywords.None, IDictionary <string, string> arguments = null) { if (eventSourceName == null) { throw new ArgumentNullException("eventSourceName"); } foreach (var item in EventSource.GetSources()) { if (item.Name.Equals(eventSourceName, StringComparison.Ordinal)) { return(FromEventSource(item, level)); } } var listener = new SystemEventSourceListener(); listener.RegisterDelay(new SystemArgs { EventSourceName = eventSourceName, Level = level, MatchAnyKeyword = matchAnyKeyword, Arguments = arguments }); return(listener); }
public void Enable(string filterAndPayloadSpecs, EventKeywords keywords = EventKeywords.All) { var args = new Dictionary<string, string>(); if (filterAndPayloadSpecs != null) args.Add("FilterAndPayloadSpecs", filterAndPayloadSpecs); EnableEvents(_diagnosticSourceEventSource, EventLevel.Verbose, keywords, args); }
/// <summary> /// Enables events for the specified event source that has the specified verbosity level or lower, and matching keyword flags. /// </summary> /// <param name="eventListener">The event listener.</param> /// <param name="eventSourceName">The name of the event source to enable events for.</param> /// <param name="level">The level of events to enable.</param> /// <param name="matchAnyKeyword">The keyword flags necessary to enable the events.</param> /// <returns> /// <see langword="false" /> if the request was deferred; otherwise, <see langword="true" />. /// </returns> /// <remarks> /// If the event source with the supplied name has already been created the request is processed immediately. Otherwise the request /// is deferred until the event source is created. /// </remarks> public static bool EnableEvents(this EventListener eventListener, string eventSourceName, EventLevel level, EventKeywords matchAnyKeyword) { return(CastToObservableEventListener(eventListener).EnableEvents(eventSourceName, level, matchAnyKeyword)); }
/// <summary> /// Writes an extended event, where the values of the event are the /// combined properties of any number of values. This method is /// intended for use in advanced logging scenarios that support a /// dynamic set of event context providers. /// Attention: This API does not check whether the event is enabled or not. /// Please use WriteMultiMerge to avoid spending CPU cycles for events that are /// not enabled. /// </summary> /// <param name="eventName"> /// The name for the event. If null, the name from eventTypes is used. /// (Note that providing the event name via the name parameter is slightly /// less efficient than using the name from eventTypes.) /// </param> /// <param name="options"> /// Optional overrides for the event, such as the level, keyword, opcode, /// activityId, and relatedActivityId. Any settings not specified by options /// are obtained from eventTypes. /// </param> /// <param name="eventTypes"> /// Information about the event and the types of the values in the event. /// Must not be null. Note that the eventTypes object should be created once and /// saved. It should not be recreated for each event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID GUID to log /// </param> /// <param name="childActivityID"> /// A pointer to the child activity ID to log (can be null) /// </param> /// <param name="values"> /// The values to include in the event. Must not be null. The number and types of /// the values must match the number and types of the fields described by the /// eventTypes parameter. /// </param> private unsafe void WriteMultiMergeInner( string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid *activityID, Guid *childActivityID, params object[] values) { #if FEATURE_MANAGED_ETW int identity = 0; byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level : eventTypes.level; byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0 ? options.opcode : eventTypes.opcode; EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0 ? options.tags : eventTypes.Tags; EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0 ? options.keywords : eventTypes.keywords; var nameInfo = eventTypes.GetNameInfo(eventName ?? eventTypes.Name, tags); if (nameInfo == null) { return; } identity = nameInfo.identity; EventDescriptor descriptor = new EventDescriptor(identity, level, opcode, (long)keywords); #if FEATURE_PERFTRACING IntPtr eventHandle = nameInfo.GetOrCreateEventHandle(m_eventPipeProvider, m_eventHandleMap, descriptor, eventTypes); Debug.Assert(eventHandle != IntPtr.Zero); #else IntPtr eventHandle = IntPtr.Zero; #endif 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); #if (!ES_BUILD_PCL && !ES_BUILD_PN) System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif try { DataCollector.ThreadInstance.Enable( scratch, eventTypes.scratchSize, descriptors + 3, eventTypes.dataCount, pins, pinCount); for (int i = 0; i < eventTypes.typeInfos.Length; i++) { var info = eventTypes.typeInfos[i]; info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(values[i])); } this.WriteEventRaw( eventName, ref descriptor, eventHandle, activityID, childActivityID, (int)(DataCollector.ThreadInstance.Finish() - descriptors), (IntPtr)descriptors); } finally { this.WriteCleanup(pins, pinCount); } } #endif // FEATURE_MANAGED_ETW }
/// <summary> /// Enables events for the specified event source that has the specified verbosity level or lower, and matching keyword flags. /// </summary> /// <param name="eventListener">The event listener.</param> /// <param name="eventSourceName">The name of the event source to enable events for.</param> /// <param name="level">The level of events to enable.</param> /// <param name="matchAnyKeyword">The keyword flags necessary to enable the events.</param> /// <param name="arguments">The arguments to be matched to enable the events.</param> /// <returns> /// <see langword="false" /> if the request was deferred; otherwise, <see langword="true" />. /// </returns> /// <remarks> /// If the event source with the supplied name has already been created the request is processed immediately. Otherwise the request /// is deferred until the event source is created. /// </remarks> public static bool EnableEvents(this EventListener eventListener, string eventSourceName, EventLevel level, EventKeywords matchAnyKeyword, IDictionary <string, string> arguments) { return(CastToObservableEventListener(eventListener).EnableEvents(eventSourceName, level, matchAnyKeyword, arguments)); }
private void WriteEvent <T>(string eventName, string instrumentationKey, IDictionary <string, string> tags, T data, EventKeywords keywords) { this.EventSourceInternal.Write( eventName, new EventSourceOptions() { Keywords = keywords }, new { PartA_iKey = instrumentationKey, PartA_Tags = tags, _B = data }); }
/// <summary> /// Initializes a new instance of the <see cref="EventSourceSettings"/> class. /// </summary> /// <param name="name">The friendly event source name.</param> /// <param name="eventSourceId">The event source id.</param> /// <param name="level">The level.</param> /// <param name="matchAnyKeyword">The match any keyword.</param> /// <exception cref="ConfigurationException">A validation exception.</exception> public EventSourceSettings(string name = null, Guid?eventSourceId = null, EventLevel level = EventLevel.LogAlways, EventKeywords matchAnyKeyword = Keywords.All) { // If no Id, Name should not be optional so we may derive an Id from it. if (!eventSourceId.HasValue || eventSourceId == Guid.Empty) { if (string.IsNullOrWhiteSpace(name)) { throw new ConfigurationException(Properties.Resources.MissingEventSourceNameAndId); } eventSourceId = TraceEventSession.GetEventSourceGuidFromName(name); } else if (!string.IsNullOrWhiteSpace(name)) { // throw and both name & Id specified throw new ConfigurationException(Properties.Resources.EventSourceAmbiguityError); } this.EventSourceId = eventSourceId.Value; this.Name = name ?? eventSourceId.ToString(); // Set a not null value for later use this.Level = level; this.MatchAnyKeyword = matchAnyKeyword; }
public bool IsEnabled(EventLevel level, EventKeywords keywords) { return(false); }
private TraceLoggingEventTypes( EventTags tags, string defaultName, TraceLoggingTypeInfo[] typeInfos) { if (defaultName == null) { throw new ArgumentNullException("defaultName"); } Contract.EndContractBlock(); this.typeInfos = typeInfos; this.name = defaultName; this.tags = tags; this.level = Statics.DefaultLevel; var collector = new TraceLoggingMetadataCollector(); foreach (var typeInfo in typeInfos) { this.level = Statics.Combine((int)typeInfo.Level, this.level); this.opcode = Statics.Combine((int)typeInfo.Opcode, this.opcode); this.keywords |= typeInfo.Keywords; typeInfo.WriteMetadata(collector, null, EventFieldFormat.Default); } this.typeMetadata = collector.GetMetadata(); this.scratchSize = collector.ScratchSize; this.dataCount = collector.DataCount; this.pinCount = collector.PinCount; }
private static string ToHex(EventKeywords value) { return(string.Format(CultureInfo.InvariantCulture, "0x{0:X}", (long)value)); }
internal TraceLoggingEventTypes( string name, EventTags tags, System.Reflection.ParameterInfo[] paramInfos) { if (name == null) { throw new ArgumentNullException("name"); } Contract.EndContractBlock(); this.typeInfos = MakeArray(paramInfos); this.name = name; this.tags = tags; this.level = Statics.DefaultLevel; var collector = new TraceLoggingMetadataCollector(); for (int i = 0; i < typeInfos.Length; ++i) { var typeInfo = typeInfos[i]; this.level = Statics.Combine((int)typeInfo.Level, this.level); this.opcode = Statics.Combine((int)typeInfo.Opcode, this.opcode); this.keywords |= typeInfo.Keywords; var paramName = paramInfos[i].Name; if (Statics.ShouldOverrideFieldName(paramName)) { paramName = typeInfo.Name; } typeInfo.WriteMetadata(collector, paramName, EventFieldFormat.Default); } this.typeMetadata = collector.GetMetadata(); this.scratchSize = collector.ScratchSize; this.dataCount = collector.DataCount; this.pinCount = collector.PinCount; }