public void Failed(Exception e) { if (_activity == null) { return; } _source?.Write(_activity.OperationName + ".Exception", e); }
private static Guid LogHttpRequestCore(DiagnosticListener diagnosticListener, HttpRequestMessage request) { Guid loggingRequestId = Guid.NewGuid(); long timestamp = Stopwatch.GetTimestamp(); diagnosticListener.Write( HttpHandlerLoggingStrings.RequestWriteName, new { Request = request, LoggingRequestId = loggingRequestId, Timestamp = timestamp } ); return loggingRequestId; }
public void InitializeDoesNotIncludeRouteGroupKeyInParametersList() { var actionContext = new ActionContext(); actionContext.RouteData = new RouteData(); actionContext.RouteData.Values.Add("controller", "account"); actionContext.RouteData.Values.Add("action", "login"); actionContext.RouteData.Values.Add(TreeRouter.RouteGroupKey, "RouteGroupKey"); var contextAccessor = HttpContextAccessorHelper.CreateHttpContextAccessor(new RequestTelemetry(), actionContext); var telemetryListener = new DiagnosticListener(TestListenerName); var initializer = new OperationNameTelemetryInitializer(contextAccessor, telemetryListener); telemetryListener.Write(OperationNameTelemetryInitializer.BeforeActionNotificationName, new { httpContext = contextAccessor.HttpContext, routeData = actionContext.RouteData }); var telemetry = new EventTelemetry(); initializer.Initialize(telemetry); Assert.Equal("GET account/login", telemetry.Context.Operation.Name); }
private static void LogHttpResponseCore(DiagnosticListener diagnosticListener, HttpResponseMessage response, Guid loggingRequestId) { // An empty loggingRequestId signifies that the request was not logged, so do // not attempt to log response. if (loggingRequestId != Guid.Empty) { long timestamp = Stopwatch.GetTimestamp(); diagnosticListener.Write( HttpHandlerLoggingStrings.ResponseWriteName, new { Response = response, LoggingRequestId = loggingRequestId, TimeStamp = timestamp } ); } }
public void LinuxNewLineConventions() { using (var eventSourceListener = new TestDiagnosticSourceEventListener()) using (var diagnosticSourceListener = new DiagnosticListener("LinuxNewLineConventionsSource")) { Assert.Equal(0, eventSourceListener.EventCount); // Turn on events with both implicit and explicit types You can have whitespace // before and after each spec. Use \n rather than \r\n eventSourceListener.Enable( " LinuxNewLineConventionsSource/TestEvent1:-cls_Point_X=cls.Point.X\n" + " LinuxNewLineConventionsSource/TestEvent2:-cls_Url=cls.Url\n" ); /***************************************************************************************/ // Emit an event that matches the first pattern. MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } }; if (diagnosticSourceListener.IsEnabled("TestEvent1")) diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("LinuxNewLineConventionsSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("3", eventSourceListener.LastEvent.Arguments["cls_Point_X"]); eventSourceListener.ResetEventCountAndLastEvent(); /***************************************************************************************/ // Emit an event that matches the second pattern. if (diagnosticSourceListener.IsEnabled("TestEvent2")) diagnosticSourceListener.Write("TestEvent2", new { prop2Str = "hello", prop2Int = 8, cls = val }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("LinuxNewLineConventionsSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName); Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("MyUrl", eventSourceListener.LastEvent.Arguments["cls_Url"]); eventSourceListener.ResetEventCountAndLastEvent(); // Emit an event that does not match either pattern. (thus will be filtered out) if (diagnosticSourceListener.IsEnabled("TestEvent3")) diagnosticSourceListener.Write("TestEvent3", new { propStr = "prop3", }); Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired. } // Make sure that there are no Diagnostic Listeners left over. DiagnosticListener.AllListeners.Subscribe(DiagnosticSourceTest.MakeObserver(delegate (DiagnosticListener listen) { Assert.True(!listen.Name.StartsWith("BuildTestSource")); })); }
public void MultiSubscriber() { using (DiagnosticListener listener = new DiagnosticListener("Testing")) { DiagnosticSource source = listener; var subscriber1Result = new List <KeyValuePair <string, object> >(); Predicate <string> subscriber1Predicate = name => (name == "DataForSubscriber1"); var subscriber1Oberserver = new ObserverToList <TelemData>(subscriber1Result); var subscriber2Result = new List <KeyValuePair <string, object> >(); Predicate <string> subscriber2Predicate = name => (name == "DataForSubscriber2"); var subscriber2Oberserver = new ObserverToList <TelemData>(subscriber2Result); // Get two subscribers going. using (var subscription1 = listener.Subscribe(subscriber1Oberserver, subscriber1Predicate)) { using (var subscription2 = listener.Subscribe(subscriber2Oberserver, subscriber2Predicate)) { // Things that neither subscribe to get filtered out. if (listener.IsEnabled("DataToFilterOut")) { listener.Write("DataToFilterOut", -1); } Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // If a Source does not use the IsEnabled, then every subscriber gets it. subscriber1Result.Clear(); subscriber2Result.Clear(); listener.Write("UnfilteredData", 3); Assert.Equal(1, subscriber1Result.Count); Assert.Equal("UnfilteredData", subscriber1Result[0].Key); Assert.Equal(3, (int)subscriber1Result[0].Value); Assert.Equal(1, subscriber2Result.Count); Assert.Equal("UnfilteredData", subscriber2Result[0].Key); Assert.Equal(3, (int)subscriber2Result[0].Value); /****************************************************/ // Filters not filter out everything, they are just a performance optimization. // Here you actually get more than you want even though you use a filter subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataForSubscriber1")) { listener.Write("DataForSubscriber1", 1); } Assert.Equal(1, subscriber1Result.Count); Assert.Equal("DataForSubscriber1", subscriber1Result[0].Key); Assert.Equal(1, (int)subscriber1Result[0].Value); // Subscriber 2 happens to get it Assert.Equal(1, subscriber2Result.Count); Assert.Equal("DataForSubscriber1", subscriber2Result[0].Key); Assert.Equal(1, (int)subscriber2Result[0].Value); /****************************************************/ subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataForSubscriber2")) { listener.Write("DataForSubscriber2", 2); } // Subscriber 1 happens to get it Assert.Equal(1, subscriber1Result.Count); Assert.Equal("DataForSubscriber2", subscriber1Result[0].Key); Assert.Equal(2, (int)subscriber1Result[0].Value); Assert.Equal(1, subscriber2Result.Count); Assert.Equal("DataForSubscriber2", subscriber2Result[0].Key); Assert.Equal(2, (int)subscriber2Result[0].Value); } // subscriber2 drops out /*********************************************************************/ /* Only Subscriber 1 is left */ /*********************************************************************/ // Things that neither subscribe to get filtered out. subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataToFilterOut")) { listener.Write("DataToFilterOut", -1); } Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // If a Source does not use the IsEnabled, then every subscriber gets it. subscriber1Result.Clear(); listener.Write("UnfilteredData", 3); Assert.Equal(1, subscriber1Result.Count); Assert.Equal("UnfilteredData", subscriber1Result[0].Key); Assert.Equal(3, (int)subscriber1Result[0].Value); // Subscriber 2 has dropped out. Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // Filters not filter out everything, they are just a performance optimization. // Here you actually get more than you want even though you use a filter subscriber1Result.Clear(); if (listener.IsEnabled("DataForSubscriber1")) { listener.Write("DataForSubscriber1", 1); } Assert.Equal(1, subscriber1Result.Count); Assert.Equal("DataForSubscriber1", subscriber1Result[0].Key); Assert.Equal(1, (int)subscriber1Result[0].Value); // Subscriber 2 has dropped out. Assert.Equal(0, subscriber2Result.Count); /****************************************************/ subscriber1Result.Clear(); if (listener.IsEnabled("DataForSubscriber2")) { listener.Write("DataForSubscriber2", 2); } // Subscriber 1 filters Assert.Equal(0, subscriber1Result.Count); // Subscriber 2 has dropped out Assert.Equal(0, subscriber2Result.Count); } // subscriber1 drops out /*********************************************************************/ /* No Subscribers are left */ /*********************************************************************/ // Things that neither subscribe to get filtered out. subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataToFilterOut")) { listener.Write("DataToFilterOut", -1); } Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // If a Source does not use the IsEnabled, then every subscriber gets it. listener.Write("UnfilteredData", 3); // No one subscribing Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // Filters not filter out everything, they are just a performance optimization. // Here you actually get more than you want even though you use a filter if (listener.IsEnabled("DataForSubscriber1")) { listener.Write("DataForSubscriber1", 1); } // No one subscribing Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ if (listener.IsEnabled("DataForSubscriber2")) { listener.Write("DataForSubscriber2", 2); } // No one subscribing Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); } }
public void TestActivities() { using (var eventSourceListener = new TestDiagnosticSourceEventListener()) using (var diagnosticSourceListener = new DiagnosticListener("TestActivitiesSource")) { Assert.Equal(0, eventSourceListener.EventCount); eventSourceListener.Enable( "TestActivitiesSource/TestActivity1Start@Activity1Start\r\n" + "TestActivitiesSource/TestActivity1Stop@Activity1Stop\r\n" + "TestActivitiesSource/TestActivity2Start@Activity2Start\r\n" + "TestActivitiesSource/TestActivity2Stop@Activity2Stop\r\n" + "TestActivitiesSource/TestEvent\r\n" ); // Start activity 1 diagnosticSourceListener.Write("TestActivity1Start", new { propStr = "start" }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("Activity1Start", eventSourceListener.LastEvent.EventSourceEventName); Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestActivity1Start", eventSourceListener.LastEvent.EventName); Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("start", eventSourceListener.LastEvent.Arguments["propStr"]); eventSourceListener.ResetEventCountAndLastEvent(); // Start nested activity 2 diagnosticSourceListener.Write("TestActivity2Start", new { propStr = "start" }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("Activity2Start", eventSourceListener.LastEvent.EventSourceEventName); Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestActivity2Start", eventSourceListener.LastEvent.EventName); Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("start", eventSourceListener.LastEvent.Arguments["propStr"]); eventSourceListener.ResetEventCountAndLastEvent(); // Send a normal event diagnosticSourceListener.Write("TestEvent", new { propStr = "event" }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("Event", eventSourceListener.LastEvent.EventSourceEventName); Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent", eventSourceListener.LastEvent.EventName); Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("event", eventSourceListener.LastEvent.Arguments["propStr"]); eventSourceListener.ResetEventCountAndLastEvent(); // Stop nested activity 2 diagnosticSourceListener.Write("TestActivity2Stop", new { propStr = "stop" }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("Activity2Stop", eventSourceListener.LastEvent.EventSourceEventName); Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestActivity2Stop", eventSourceListener.LastEvent.EventName); Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("stop", eventSourceListener.LastEvent.Arguments["propStr"]); eventSourceListener.ResetEventCountAndLastEvent(); // Stop activity 1 diagnosticSourceListener.Write("TestActivity1Stop", new { propStr = "stop" }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("Activity1Stop", eventSourceListener.LastEvent.EventSourceEventName); Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestActivity1Stop", eventSourceListener.LastEvent.EventName); Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("stop", eventSourceListener.LastEvent.Arguments["propStr"]); eventSourceListener.ResetEventCountAndLastEvent(); } }
public void TestNoImplicitTransforms() { using (var eventSourceListener = new TestDiagnosticSourceEventListener()) using (var diagnosticSourceListener = new DiagnosticListener("TestNoImplicitTransformsSource")) { Assert.Equal(0, eventSourceListener.EventCount); // use the - prefix to suppress the implicit properties. Thus you should only get propStr and Url. eventSourceListener.Enable("TestNoImplicitTransformsSource/TestEvent1:-propStr;cls.Url"); /***************************************************************************************/ // Emit an event that matches the first pattern. MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } }; if (diagnosticSourceListener.IsEnabled("TestEvent1")) diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val, propStr2 = "there" }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestNoImplicitTransformsSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]); Assert.Equal("MyUrl", eventSourceListener.LastEvent.Arguments["Url"]); eventSourceListener.ResetEventCountAndLastEvent(); } }
public void TestSpecificEvents() { using (var eventSourceListener = new TestDiagnosticSourceEventListener()) using (var diagnosticSourceListener = new DiagnosticListener("TestSpecificEventsSource")) { Assert.Equal(0, eventSourceListener.EventCount); // Turn on events with both implicit and explicit types You can have whitespace // before and after each spec. eventSourceListener.Enable( " TestSpecificEventsSource/TestEvent1:cls_Point_X=cls.Point.X;cls_Point_Y=cls.Point.Y\r\n" + " TestSpecificEventsSource/TestEvent2:cls_Url=cls.Url\r\n" ); /***************************************************************************************/ // Emit an event that matches the first pattern. MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } }; if (diagnosticSourceListener.IsEnabled("TestEvent1")) diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestSpecificEventsSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(4, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]); Assert.Equal("4", eventSourceListener.LastEvent.Arguments["propInt"]); Assert.Equal("3", eventSourceListener.LastEvent.Arguments["cls_Point_X"]); Assert.Equal("5", eventSourceListener.LastEvent.Arguments["cls_Point_Y"]); eventSourceListener.ResetEventCountAndLastEvent(); /***************************************************************************************/ // Emit an event that matches the second pattern. if (diagnosticSourceListener.IsEnabled("TestEvent2")) diagnosticSourceListener.Write("TestEvent2", new { prop2Str = "hello", prop2Int = 8, cls = val }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestSpecificEventsSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName); Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("hello", eventSourceListener.LastEvent.Arguments["prop2Str"]); Assert.Equal("8", eventSourceListener.LastEvent.Arguments["prop2Int"]); Assert.Equal("MyUrl", eventSourceListener.LastEvent.Arguments["cls_Url"]); eventSourceListener.ResetEventCountAndLastEvent(); // Emit an event that does not match either pattern. (thus will be filtered out) if (diagnosticSourceListener.IsEnabled("TestEvent3")) diagnosticSourceListener.Write("TestEvent3", new { propStr = "prop3", }); Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired. /***************************************************************************************/ // Emit an event from another diagnostic source with the same event name. // It will be filtered out. using (var diagnosticSourceListener2 = new DiagnosticListener("TestSpecificEventsSource2")) { if (diagnosticSourceListener2.IsEnabled("TestEvent1")) diagnosticSourceListener2.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val }); } Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired. // Disable all the listener and insure that no more events come through. eventSourceListener.Disable(); diagnosticSourceListener.Write("TestEvent1", null); diagnosticSourceListener.Write("TestEvent2", null); Assert.Equal(0, eventSourceListener.EventCount); // No Event should be received. } // Make sure that there are no Diagnostic Listeners left over. DiagnosticListener.AllListeners.Subscribe(DiagnosticSourceTest.MakeObserver(delegate (DiagnosticListener listen) { Assert.True(!listen.Name.StartsWith("BuildTestSource")); })); }
public void TestWildCardEventName() { using (var eventSourceListener = new TestDiagnosticSourceEventListener()) using (var diagnosticSourceListener = new DiagnosticListener("TestWildCardEventNameSource")) { Assert.Equal(0, eventSourceListener.EventCount); // Turn on events with both implicit and explicit types eventSourceListener.Enable("TestWildCardEventNameSource"); /***************************************************************************************/ // Emit an event, check that all implicit properties are generated MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } }; if (diagnosticSourceListener.IsEnabled("TestEvent1")) { diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val }); } Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestWildCardEventNameSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]); Assert.Equal("4", eventSourceListener.LastEvent.Arguments["propInt"]); eventSourceListener.ResetEventCountAndLastEvent(); /***************************************************************************************/ // Emit the same event, with a different set of implicit properties if (diagnosticSourceListener.IsEnabled("TestEvent1")) { diagnosticSourceListener.Write("TestEvent1", new { propStr2 = "hi2", cls = val }); } Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestWildCardEventNameSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name Assert.Equal("hi2", eventSourceListener.LastEvent.Arguments["propStr2"]); eventSourceListener.ResetEventCountAndLastEvent(); /***************************************************************************************/ // Emit an event from another diagnostic source with the same event name. // It will be filtered out. using (var diagnosticSourceListener2 = new DiagnosticListener("TestWildCardEventNameSource2")) { if (diagnosticSourceListener2.IsEnabled("TestEvent1")) { diagnosticSourceListener2.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val }); } } Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired. } }
/// <summary> /// Notifies listeners that activity was ended and lost during execution. /// </summary> /// <param name="activity">Activity to notify about.</param> /// <param name="context">Current HttpContext.</param> public static void StopLostActivity(Activity activity, HttpContext context) { context.Items[ActivityKey] = null; AspNetListener.Write(AspNetActivityLostStopName, new { activity }); AspNetTelemetryCorrelationEventSource.Log.ActivityStopped(activity.Id, AspNetActivityLostStopName); }
private async ValueTask <HttpResponseMessage> SendAsyncCore(HttpRequestMessage request, bool async, CancellationToken cancellationToken) { // HttpClientHandler is responsible to call static DiagnosticsHandler.IsEnabled() before forwarding request here. // It will check if propagation is on (because parent Activity exists or there is a listener) or off (forcibly disabled) // This code won't be called unless consumer unsubscribes from DiagnosticListener right after the check. // So some requests happening right after subscription starts might not be instrumented. Similarly, // when consumer unsubscribes, extra requests might be instrumented if (request == null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } Activity? activity = null; DiagnosticListener diagnosticListener = Settings.s_diagnosticListener; // if there is no listener, but propagation is enabled (with previous IsEnabled() check) // do not write any events just start/stop Activity and propagate Ids if (!diagnosticListener.IsEnabled()) { activity = new Activity(DiagnosticsHandlerLoggingStrings.ActivityName); activity.Start(); InjectHeaders(activity, request); try { return(async ? await base.SendAsync(request, cancellationToken).ConfigureAwait(false) : base.Send(request, cancellationToken)); } finally { activity.Stop(); } } Guid loggingRequestId = Guid.Empty; // There is a listener. Check if listener wants to be notified about HttpClient Activities if (diagnosticListener.IsEnabled(DiagnosticsHandlerLoggingStrings.ActivityName, request)) { activity = new Activity(DiagnosticsHandlerLoggingStrings.ActivityName); // Only send start event to users who subscribed for it, but start activity anyway if (diagnosticListener.IsEnabled(DiagnosticsHandlerLoggingStrings.ActivityStartName)) { diagnosticListener.StartActivity(activity, new ActivityStartData(request)); } else { activity.Start(); } } // try to write System.Net.Http.Request event (deprecated) if (diagnosticListener.IsEnabled(DiagnosticsHandlerLoggingStrings.RequestWriteNameDeprecated)) { long timestamp = Stopwatch.GetTimestamp(); loggingRequestId = Guid.NewGuid(); diagnosticListener.Write(DiagnosticsHandlerLoggingStrings.RequestWriteNameDeprecated, new RequestData(request, loggingRequestId, timestamp)); } // If we are on at all, we propagate current activity information Activity?currentActivity = Activity.Current; if (currentActivity != null) { InjectHeaders(currentActivity, request); } HttpResponseMessage?response = null; TaskStatus taskStatus = TaskStatus.RanToCompletion; try { response = async ? await base.SendAsync(request, cancellationToken).ConfigureAwait(false) : base.Send(request, cancellationToken); return(response); } catch (OperationCanceledException) { taskStatus = TaskStatus.Canceled; // we'll report task status in HttpRequestOut.Stop throw; } catch (Exception ex) { taskStatus = TaskStatus.Faulted; if (diagnosticListener.IsEnabled(DiagnosticsHandlerLoggingStrings.ExceptionEventName)) { // If request was initially instrumented, Activity.Current has all necessary context for logging // Request is passed to provide some context if instrumentation was disabled and to avoid // extensive Activity.Tags usage to tunnel request properties diagnosticListener.Write(DiagnosticsHandlerLoggingStrings.ExceptionEventName, new ExceptionData(ex, request)); } throw; } finally { // always stop activity if it was started if (activity != null) { diagnosticListener.StopActivity(activity, new ActivityStopData( response, // If request is failed or cancelled, there is no response, therefore no information about request; // pass the request in the payload, so consumers can have it in Stop for failed/canceled requests // and not retain all requests in Start request, taskStatus)); } // Try to write System.Net.Http.Response event (deprecated) if (diagnosticListener.IsEnabled(DiagnosticsHandlerLoggingStrings.ResponseWriteNameDeprecated)) { long timestamp = Stopwatch.GetTimestamp(); diagnosticListener.Write(DiagnosticsHandlerLoggingStrings.ResponseWriteNameDeprecated, new ResponseData( response, loggingRequestId, timestamp, taskStatus)); } } }
public ISubscription Subscribe(string @namespace, string eventTypeFilter, Func <EventMessage, Task> handler) { if (string.IsNullOrEmpty(@namespace)) { throw new ArgumentNullException(nameof(@namespace)); } if (string.IsNullOrEmpty(eventTypeFilter)) { throw new ArgumentNullException(nameof(eventTypeFilter)); } if (handler == null) { throw new ArgumentNullException(nameof(handler)); } var channel = _conn.CreateModel(); channel.ExchangeDeclare(@namespace, ChannelType); var queueName = channel.QueueDeclare().QueueName; channel.QueueBind(queueName, @namespace, eventTypeFilter); var consumer = new AsyncEventingBasicConsumer(channel); async Task EventHandler(object sender, BasicDeliverEventArgs @event) { var eventMessage = new EventMessage { Namespace = @event.Exchange, RoutingKey = @event.RoutingKey, EventType = @event.BasicProperties.Type, ContentType = @event.BasicProperties.ContentType, ContentEncoding = @event.BasicProperties.ContentEncoding, Timestamp = DateTimeOffset.FromUnixTimeMilliseconds(@event.BasicProperties.Timestamp.UnixTime), MessageBody = @event.Body }; Activity activity = null; if (_diagnostics != null && _diagnostics.IsEnabled() && _diagnostics.IsEnabled(DiagnosticOperations.MessageHandling, @event)) { activity = new Activity(DiagnosticOperations.MessageHandling); if (@event.BasicProperties != null) { if (!string.IsNullOrEmpty(@event.BasicProperties.CorrelationId)) { activity.SetParentId(@event.BasicProperties.CorrelationId); } if (@event.BasicProperties.Headers != null && @event.BasicProperties.Headers.Any()) { @event.BasicProperties.Headers.ToList().ForEach(i => activity.AddBaggage(i.Key, i.Value.ToString())); } } _diagnostics.StartActivity(activity, @event); } try { await handler(eventMessage); } catch (Exception e) { if (_diagnostics != null && _diagnostics.IsEnabled() && _diagnostics.IsEnabled(DiagnosticOperations.MessageHandling, @event)) { _diagnostics.Write(DiagnosticOperations.MessageHandlingError, e); } } finally { if (_diagnostics != null && _diagnostics.IsEnabled() && _diagnostics.IsEnabled(DiagnosticOperations.MessageHandling, @event) && activity != null) { _diagnostics.StopActivity(activity, @event); } } } consumer.Received += EventHandler; channel.BasicConsume(consumer, queueName, true); return(new Subscription(@namespace, eventTypeFilter, () => consumer.Received -= EventHandler)); }
public void InitializeSetsTelemetryOperationNameToControllerFromActionContext() { var actionContext = new ActionContext(); actionContext.RouteData = new RouteData(); actionContext.RouteData.Values.Add("controller", "home"); var contextAccessor = HttpContextAccessorHelper.CreateHttpContextAccessor(new RequestTelemetry(), actionContext); var telemetryListener = new DiagnosticListener(TestListenerName); var initializer = new OperationNameTelemetryInitializer(contextAccessor, telemetryListener); telemetryListener.Write(OperationNameTelemetryInitializer.BeforeActionNotificationName, new { httpContext = contextAccessor.HttpContext, routeData = actionContext.RouteData }); var telemetry = new EventTelemetry(); initializer.Initialize(telemetry); Assert.Equal("GET home", telemetry.Context.Operation.Name); }
public void TestWildCardSourceName() { using (var eventSourceListener = new TestDiagnosticSourceEventListener()) using (var diagnosticSourceListener1 = new DiagnosticListener("TestWildCardSourceName1")) using (var diagnosticSourceListener2 = new DiagnosticListener("TestWildCardSourceName2")) { eventSourceListener.Filter = (DiagnosticSourceEvent evnt) => evnt.SourceName.StartsWith("TestWildCardSourceName"); // Turn On Everything. Note that because of concurrent testing, we may get other sources as well. // but we filter them out because we set eventSourceListener.Filter. eventSourceListener.Enable(""); Assert.True(diagnosticSourceListener1.IsEnabled("TestEvent1")); Assert.True(diagnosticSourceListener1.IsEnabled("TestEvent2")); Assert.True(diagnosticSourceListener2.IsEnabled("TestEvent1")); Assert.True(diagnosticSourceListener2.IsEnabled("TestEvent2")); Assert.Equal(0, eventSourceListener.EventCount); diagnosticSourceListener1.Write("TestEvent1", new { prop111 = "prop111Val", prop112 = 112 }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestWildCardSourceName1", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("prop111Val", eventSourceListener.LastEvent.Arguments["prop111"]); Assert.Equal("112", eventSourceListener.LastEvent.Arguments["prop112"]); eventSourceListener.ResetEventCountAndLastEvent(); diagnosticSourceListener1.Write("TestEvent2", new { prop121 = "prop121Val", prop122 = 122 }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestWildCardSourceName1", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName); Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("prop121Val", eventSourceListener.LastEvent.Arguments["prop121"]); Assert.Equal("122", eventSourceListener.LastEvent.Arguments["prop122"]); eventSourceListener.ResetEventCountAndLastEvent(); diagnosticSourceListener2.Write("TestEvent1", new { prop211 = "prop211Val", prop212 = 212 }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestWildCardSourceName2", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("prop211Val", eventSourceListener.LastEvent.Arguments["prop211"]); Assert.Equal("212", eventSourceListener.LastEvent.Arguments["prop212"]); eventSourceListener.ResetEventCountAndLastEvent(); diagnosticSourceListener2.Write("TestEvent2", new { prop221 = "prop221Val", prop222 = 122 }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestWildCardSourceName2", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName); Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("prop221Val", eventSourceListener.LastEvent.Arguments["prop221"]); Assert.Equal("122", eventSourceListener.LastEvent.Arguments["prop222"]); eventSourceListener.ResetEventCountAndLastEvent(); } }
public void TestWildCardEventName() { using (var eventSourceListener = new TestDiagnosticSourceEventListener()) using (var diagnosticSourceListener = new DiagnosticListener("TestWildCardEventNameSource")) { Assert.Equal(0, eventSourceListener.EventCount); // Turn on events with both implicit and explicit types eventSourceListener.Enable("TestWildCardEventNameSource"); /***************************************************************************************/ // Emit an event, check that all implicit properties are generated MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } }; if (diagnosticSourceListener.IsEnabled("TestEvent1")) diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestWildCardEventNameSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]); Assert.Equal("4", eventSourceListener.LastEvent.Arguments["propInt"]); eventSourceListener.ResetEventCountAndLastEvent(); /***************************************************************************************/ // Emit the same event, with a different set of implicit properties if (diagnosticSourceListener.IsEnabled("TestEvent1")) diagnosticSourceListener.Write("TestEvent1", new { propStr2 = "hi2", cls = val }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestWildCardEventNameSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("hi2", eventSourceListener.LastEvent.Arguments["propStr2"]); eventSourceListener.ResetEventCountAndLastEvent(); /***************************************************************************************/ // Emit an event from another diagnostic source with the same event name. // It will be filtered out. using (var diagnosticSourceListener2 = new DiagnosticListener("TestWildCardEventNameSource2")) { if (diagnosticSourceListener2.IsEnabled("TestEvent1")) diagnosticSourceListener2.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val }); } Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired. } }
public void TestNulls() { using (var eventSourceListener = new TestDiagnosticSourceEventListener()) using (var diagnosticSourceListener = new DiagnosticListener("TestNullsTestSource")) { Assert.Equal(0, eventSourceListener.EventCount); // Turn on events with both implicit and explicit types eventSourceListener.Enable("TestNullsTestSource/TestEvent1:cls.Url;cls_Point_X=cls.Point.X"); /***************************************************************************************/ // Emit a null arguments object. if (diagnosticSourceListener.IsEnabled("TestEvent1")) diagnosticSourceListener.Write("TestEvent1", null); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(0, eventSourceListener.LastEvent.Arguments.Count); eventSourceListener.ResetEventCountAndLastEvent(); /***************************************************************************************/ // Emit an arguments object with nulls in it. MyClass val = null; string strVal = null; if (diagnosticSourceListener.IsEnabled("TestEvent1")) diagnosticSourceListener.Write("TestEvent1", new { cls = val, propStr = "propVal1", propStrNull = strVal }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]); Assert.Equal("", eventSourceListener.LastEvent.Arguments["propStrNull"]); // null strings get turned into empty strings eventSourceListener.ResetEventCountAndLastEvent(); /***************************************************************************************/ // Emit an arguments object that points at null things MyClass val1 = new MyClass() { Url = "myUrlVal", Point = null }; if (diagnosticSourceListener.IsEnabled("TestEvent1")) diagnosticSourceListener.Write("TestEvent1", new { cls = val1, propStr = "propVal1" }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]); Assert.Equal("myUrlVal", eventSourceListener.LastEvent.Arguments["Url"]); eventSourceListener.ResetEventCountAndLastEvent(); /***************************************************************************************/ // Emit an arguments object that points at null things (variation 2) MyClass val2 = new MyClass() { Url = null, Point = new MyPoint() { X = 8, Y = 9 } }; if (diagnosticSourceListener.IsEnabled("TestEvent1")) diagnosticSourceListener.Write("TestEvent1", new { cls = val2, propStr = "propVal1" }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]); Assert.Equal("8", eventSourceListener.LastEvent.Arguments["cls_Point_X"]); eventSourceListener.ResetEventCountAndLastEvent(); } }
public void TestShortcutKeywords() { using (var eventSourceListener = new TestDiagnosticSourceEventListener()) // These are look-alikes for the real ones. using (var aspNetCoreSource = new DiagnosticListener("Microsoft.AspNetCore")) using (var entityFrameworkCoreSource = new DiagnosticListener("Microsoft.EntityFrameworkCore")) { // These are from DiagnosticSourceEventListener. var Messages = (EventKeywords)0x1; var Events = (EventKeywords)0x2; var AspNetCoreHosting = (EventKeywords)0x1000; var EntityFrameworkCoreCommands = (EventKeywords)0x2000; // Turn on listener using just the keywords eventSourceListener.Enable(null, Messages | Events | AspNetCoreHosting | EntityFrameworkCoreCommands); Assert.Equal(0, eventSourceListener.EventCount); // Start a ASP.NET Request aspNetCoreSource.Write("Microsoft.AspNetCore.Hosting.BeginRequest", new { httpContext = new { Request = new { Method = "Get", Host = "MyHost", Path = "MyPath", QueryString = "MyQuery" } } }); // Check that the morphs work as expected. Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("Activity1Start", eventSourceListener.LastEvent.EventSourceEventName); Assert.Equal("Microsoft.AspNetCore", eventSourceListener.LastEvent.SourceName); Assert.Equal("Microsoft.AspNetCore.Hosting.BeginRequest", eventSourceListener.LastEvent.EventName); Assert.True(4 <= eventSourceListener.LastEvent.Arguments.Count); Debug.WriteLine("Arg Keys = " + string.Join(" ", eventSourceListener.LastEvent.Arguments.Keys)); Debug.WriteLine("Arg Values = " + string.Join(" ", eventSourceListener.LastEvent.Arguments.Values)); Assert.Equal("Get", eventSourceListener.LastEvent.Arguments["Method"]); Assert.Equal("MyHost", eventSourceListener.LastEvent.Arguments["Host"]); Assert.Equal("MyPath", eventSourceListener.LastEvent.Arguments["Path"]); Assert.Equal("MyQuery", eventSourceListener.LastEvent.Arguments["QueryString"]); eventSourceListener.ResetEventCountAndLastEvent(); // Start a SQL command entityFrameworkCoreSource.Write("Microsoft.EntityFrameworkCore.BeforeExecuteCommand", new { Command = new { Connection = new { DataSource = "MyDataSource", Database = "MyDatabase", }, CommandText = "MyCommand" } }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("Activity2Start", eventSourceListener.LastEvent.EventSourceEventName); Assert.Equal("Microsoft.EntityFrameworkCore", eventSourceListener.LastEvent.SourceName); Assert.Equal("Microsoft.EntityFrameworkCore.BeforeExecuteCommand", eventSourceListener.LastEvent.EventName); Assert.True(3 <= eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("MyDataSource", eventSourceListener.LastEvent.Arguments["DataSource"]); Assert.Equal("MyDatabase", eventSourceListener.LastEvent.Arguments["Database"]); Assert.Equal("MyCommand", eventSourceListener.LastEvent.Arguments["CommandText"]); eventSourceListener.ResetEventCountAndLastEvent(); // Stop the SQL command entityFrameworkCoreSource.Write("Microsoft.EntityFrameworkCore.AfterExecuteCommand", null); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("Activity2Stop", eventSourceListener.LastEvent.EventSourceEventName); Assert.Equal("Microsoft.EntityFrameworkCore", eventSourceListener.LastEvent.SourceName); Assert.Equal("Microsoft.EntityFrameworkCore.AfterExecuteCommand", eventSourceListener.LastEvent.EventName); eventSourceListener.ResetEventCountAndLastEvent(); // Stop the ASP.NET request. aspNetCoreSource.Write("Microsoft.AspNetCore.Hosting.EndRequest", new { httpContext = new { Response = new { StatusCode = "200" }, TraceIdentifier = "MyTraceId" } }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("Activity1Stop", eventSourceListener.LastEvent.EventSourceEventName); Assert.Equal("Microsoft.AspNetCore", eventSourceListener.LastEvent.SourceName); Assert.Equal("Microsoft.AspNetCore.Hosting.EndRequest", eventSourceListener.LastEvent.EventName); Assert.True(2 <= eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("MyTraceId", eventSourceListener.LastEvent.Arguments["TraceIdentifier"]); Assert.Equal("200", eventSourceListener.LastEvent.Arguments["StatusCode"]); eventSourceListener.ResetEventCountAndLastEvent(); } }
public void TestBadProperties() { using (var eventSourceListener = new TestDiagnosticSourceEventListener()) using (var diagnosticSourceListener = new DiagnosticListener("TestBadPropertiesSource")) { Assert.Equal(0, eventSourceListener.EventCount); // This has a syntax error in the Url case, so it should be ignored. eventSourceListener.Enable("TestBadPropertiesSource/TestEvent1:cls.Ur-+l"); /***************************************************************************************/ // Emit an event that matches the first pattern. MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } }; if (diagnosticSourceListener.IsEnabled("TestEvent1")) diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestBadPropertiesSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]); Assert.Equal("4", eventSourceListener.LastEvent.Arguments["propInt"]); eventSourceListener.ResetEventCountAndLastEvent(); } }
public void LinuxNewLineConventions() { using (var eventSourceListener = new TestDiagnosticSourceEventListener()) using (var diagnosticSourceListener = new DiagnosticListener("LinuxNewLineConventionsSource")) { Assert.Equal(0, eventSourceListener.EventCount); // Turn on events with both implicit and explicit types You can have whitespace // before and after each spec. Use \n rather than \r\n eventSourceListener.Enable( " LinuxNewLineConventionsSource/TestEvent1:-cls_Point_X=cls.Point.X\n" + " LinuxNewLineConventionsSource/TestEvent2:-cls_Url=cls.Url\n" ); /***************************************************************************************/ // Emit an event that matches the first pattern. MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } }; if (diagnosticSourceListener.IsEnabled("TestEvent1")) { diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val }); } Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("LinuxNewLineConventionsSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("3", eventSourceListener.LastEvent.Arguments["cls_Point_X"]); eventSourceListener.ResetEventCountAndLastEvent(); /***************************************************************************************/ // Emit an event that matches the second pattern. if (diagnosticSourceListener.IsEnabled("TestEvent2")) { diagnosticSourceListener.Write("TestEvent2", new { prop2Str = "hello", prop2Int = 8, cls = val }); } Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("LinuxNewLineConventionsSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName); Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("MyUrl", eventSourceListener.LastEvent.Arguments["cls_Url"]); eventSourceListener.ResetEventCountAndLastEvent(); // Emit an event that does not match either pattern. (thus will be filtered out) if (diagnosticSourceListener.IsEnabled("TestEvent3")) { diagnosticSourceListener.Write("TestEvent3", new { propStr = "prop3", }); } Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired. } // Make sure that there are no Diagnostic Listeners left over. DiagnosticListener.AllListeners.Subscribe(DiagnosticSourceTest.MakeObserver(delegate(DiagnosticListener listen) { Assert.True(!listen.Name.StartsWith("BuildTestSource")); })); }
public void TestShortcutKeywords() { using (var eventSourceListener = new TestDiagnosticSourceEventListener()) // These are look-alikes for the real ones. using (var aspNetCoreSource = new DiagnosticListener("Microsoft.AspNetCore")) using (var entityFrameworkCoreSource = new DiagnosticListener("Microsoft.EntityFrameworkCore")) { // These are from DiagnosticSourceEventListener. var Messages = (EventKeywords)0x1; var Events = (EventKeywords)0x2; var AspNetCoreHosting = (EventKeywords)0x1000; var EntityFrameworkCoreCommands = (EventKeywords)0x2000; // Turn on listener using just the keywords eventSourceListener.Enable(null, Messages | Events | AspNetCoreHosting | EntityFrameworkCoreCommands); Assert.Equal(0, eventSourceListener.EventCount); // Start a ASP.NET Request aspNetCoreSource.Write("Microsoft.AspNetCore.Hosting.BeginRequest", new { httpContext = new { Request = new { Method = "Get", Host = "MyHost", Path = "MyPath", QueryString = "MyQuery" } } }); // Check that the morphs work as expected. Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("Activity1Start", eventSourceListener.LastEvent.EventSourceEventName); Assert.Equal("Microsoft.AspNetCore", eventSourceListener.LastEvent.SourceName); Assert.Equal("Microsoft.AspNetCore.Hosting.BeginRequest", eventSourceListener.LastEvent.EventName); Assert.True(4 <= eventSourceListener.LastEvent.Arguments.Count); Debug.WriteLine("Arg Keys = " + string.Join(" ", eventSourceListener.LastEvent.Arguments.Keys)); Debug.WriteLine("Arg Values = " + string.Join(" ", eventSourceListener.LastEvent.Arguments.Values)); Assert.Equal("Get", eventSourceListener.LastEvent.Arguments["Method"]); Assert.Equal("MyHost", eventSourceListener.LastEvent.Arguments["Host"]); Assert.Equal("MyPath", eventSourceListener.LastEvent.Arguments["Path"]); Assert.Equal("MyQuery", eventSourceListener.LastEvent.Arguments["QueryString"]); eventSourceListener.ResetEventCountAndLastEvent(); // Start a SQL command entityFrameworkCoreSource.Write("Microsoft.EntityFrameworkCore.BeforeExecuteCommand", new { Command = new { Connection = new { DataSource = "MyDataSource", Database = "MyDatabase", }, CommandText = "MyCommand" } }); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("Activity2Start", eventSourceListener.LastEvent.EventSourceEventName); Assert.Equal("Microsoft.EntityFrameworkCore", eventSourceListener.LastEvent.SourceName); Assert.Equal("Microsoft.EntityFrameworkCore.BeforeExecuteCommand", eventSourceListener.LastEvent.EventName); Assert.True(3 <= eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("MyDataSource", eventSourceListener.LastEvent.Arguments["DataSource"]); Assert.Equal("MyDatabase", eventSourceListener.LastEvent.Arguments["Database"]); Assert.Equal("MyCommand", eventSourceListener.LastEvent.Arguments["CommandText"]); eventSourceListener.ResetEventCountAndLastEvent(); // Stop the SQL command entityFrameworkCoreSource.Write("Microsoft.EntityFrameworkCore.AfterExecuteCommand", null); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("Activity2Stop", eventSourceListener.LastEvent.EventSourceEventName); Assert.Equal("Microsoft.EntityFrameworkCore", eventSourceListener.LastEvent.SourceName); Assert.Equal("Microsoft.EntityFrameworkCore.AfterExecuteCommand", eventSourceListener.LastEvent.EventName); eventSourceListener.ResetEventCountAndLastEvent(); // Stop the ASP.NET reqeust. aspNetCoreSource.Write("Microsoft.AspNetCore.Hosting.EndRequest", null); Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("Activity1Stop", eventSourceListener.LastEvent.EventSourceEventName); Assert.Equal("Microsoft.AspNetCore", eventSourceListener.LastEvent.SourceName); Assert.Equal("Microsoft.AspNetCore.Hosting.EndRequest", eventSourceListener.LastEvent.EventName); eventSourceListener.ResetEventCountAndLastEvent(); } }
public void TestSpecificEvents() { using (var eventSourceListener = new TestDiagnosticSourceEventListener()) using (var diagnosticSourceListener = new DiagnosticListener("TestSpecificEventsSource")) { Assert.Equal(0, eventSourceListener.EventCount); // Turn on events with both implicit and explicit types You can have whitespace // before and after each spec. eventSourceListener.Enable( " TestSpecificEventsSource/TestEvent1:cls_Point_X=cls.Point.X;cls_Point_Y=cls.Point.Y\r\n" + " TestSpecificEventsSource/TestEvent2:cls_Url=cls.Url\r\n" ); /***************************************************************************************/ // Emit an event that matches the first pattern. MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } }; if (diagnosticSourceListener.IsEnabled("TestEvent1")) { diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val }); } Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestSpecificEventsSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(4, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]); Assert.Equal("4", eventSourceListener.LastEvent.Arguments["propInt"]); Assert.Equal("3", eventSourceListener.LastEvent.Arguments["cls_Point_X"]); Assert.Equal("5", eventSourceListener.LastEvent.Arguments["cls_Point_Y"]); eventSourceListener.ResetEventCountAndLastEvent(); /***************************************************************************************/ // Emit an event that matches the second pattern. if (diagnosticSourceListener.IsEnabled("TestEvent2")) { diagnosticSourceListener.Write("TestEvent2", new { prop2Str = "hello", prop2Int = 8, cls = val }); } Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestSpecificEventsSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName); Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("hello", eventSourceListener.LastEvent.Arguments["prop2Str"]); Assert.Equal("8", eventSourceListener.LastEvent.Arguments["prop2Int"]); Assert.Equal("MyUrl", eventSourceListener.LastEvent.Arguments["cls_Url"]); eventSourceListener.ResetEventCountAndLastEvent(); // Emit an event that does not match either pattern. (thus will be filtered out) if (diagnosticSourceListener.IsEnabled("TestEvent3")) { diagnosticSourceListener.Write("TestEvent3", new { propStr = "prop3", }); } Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired. /***************************************************************************************/ // Emit an event from another diagnostic source with the same event name. // It will be filtered out. using (var diagnosticSourceListener2 = new DiagnosticListener("TestSpecificEventsSource2")) { if (diagnosticSourceListener2.IsEnabled("TestEvent1")) { diagnosticSourceListener2.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val }); } } Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired. // Disable all the listener and insure that no more events come through. eventSourceListener.Disable(); diagnosticSourceListener.Write("TestEvent1", null); diagnosticSourceListener.Write("TestEvent2", null); Assert.Equal(0, eventSourceListener.EventCount); // No Event should be received. } // Make sure that there are no Diagnostic Listeners left over. DiagnosticListener.AllListeners.Subscribe(DiagnosticSourceTest.MakeObserver(delegate(DiagnosticListener listen) { Assert.True(!listen.Name.StartsWith("BuildTestSource")); })); }
public void TestNulls() { using (var eventSourceListener = new TestDiagnosticSourceEventListener()) using (var diagnosticSourceListener = new DiagnosticListener("TestNullsTestSource")) { Assert.Equal(0, eventSourceListener.EventCount); // Turn on events with both implicit and explicit types eventSourceListener.Enable("TestNullsTestSource/TestEvent1:cls.Url;cls_Point_X=cls.Point.X"); /***************************************************************************************/ // Emit a null arguments object. if (diagnosticSourceListener.IsEnabled("TestEvent1")) { diagnosticSourceListener.Write("TestEvent1", null); } Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(0, eventSourceListener.LastEvent.Arguments.Count); eventSourceListener.ResetEventCountAndLastEvent(); /***************************************************************************************/ // Emit an arguments object with nulls in it. MyClass val = null; string strVal = null; if (diagnosticSourceListener.IsEnabled("TestEvent1")) { diagnosticSourceListener.Write("TestEvent1", new { cls = val, propStr = "propVal1", propStrNull = strVal }); } Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]); Assert.Equal("", eventSourceListener.LastEvent.Arguments["propStrNull"]); // null strings get turned into empty strings eventSourceListener.ResetEventCountAndLastEvent(); /***************************************************************************************/ // Emit an arguments object that points at null things MyClass val1 = new MyClass() { Url = "myUrlVal", Point = null }; if (diagnosticSourceListener.IsEnabled("TestEvent1")) { diagnosticSourceListener.Write("TestEvent1", new { cls = val1, propStr = "propVal1" }); } Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]); Assert.Equal("myUrlVal", eventSourceListener.LastEvent.Arguments["Url"]); eventSourceListener.ResetEventCountAndLastEvent(); /***************************************************************************************/ // Emit an arguments object that points at null things (variation 2) MyClass val2 = new MyClass() { Url = null, Point = new MyPoint() { X = 8, Y = 9 } }; if (diagnosticSourceListener.IsEnabled("TestEvent1")) { diagnosticSourceListener.Write("TestEvent1", new { cls = val2, propStr = "propVal1" }); } Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted. Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName); Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName); Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count); Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]); Assert.Equal("8", eventSourceListener.LastEvent.Arguments["cls_Point_X"]); eventSourceListener.ResetEventCountAndLastEvent(); } }
public static void DiagnosticSourceTest() { #region DiagnosticSource var diagnosticListener = new DiagnosticListener(DiagnosticStrings.DiagnosticListenerName); ////订阅方法一 //DiagnosticListener.AllListeners.Subscribe(new MyObserver<DiagnosticListener>(listener => //{ // //判断发布者的名字 // if (listener.Name == DiagnosticStrings.DiagnosticListenerName) // { // //获取订阅信息 // listener.Subscribe(new MyObserver<KeyValuePair<string, object>>(listenerData => // { // Console.WriteLine($"监听名称:{listenerData.Key}"); // dynamic data = listenerData.Value; // Console.WriteLine(data.Sql); // })); // } //})); ////订阅方法二 DiagnosticListener.AllListeners.Subscribe(new MyObserver <DiagnosticListener>(listener => { if (listener.Name == DiagnosticStrings.DiagnosticListenerName) { //适配订阅 listener.SubscribeWithAdapter(new MyDiagnosticListener()); } })); //订阅方法三 //diagnosticListener.SubscribeWithAdapter(new MyDiagnosticListener()); diagnosticListener.SubscribeWithAdapter(new SqlBuilderDiagnosticListener(null)); //发送日志诊断消息 if (diagnosticListener.IsEnabled(DiagnosticStrings.BeforeExecute) && diagnosticListener.IsEnabled(DiagnosticStrings.AfterExecute) && diagnosticListener.IsEnabled(DiagnosticStrings.ErrorExecute)) { var message = new DiagnosticsMessage { Sql = "select * from table", Parameters = new Dictionary <string, object> { ["key"] = "123" }, Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }; diagnosticListener.Write( DiagnosticStrings.BeforeExecute, message); message.ElapsedMilliseconds = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - message.Timestamp; diagnosticListener.Write( DiagnosticStrings.AfterExecute, message); message.ElapsedMilliseconds = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - message.Timestamp; message.Exception = new Exception("测试异常"); diagnosticListener.Write( DiagnosticStrings.ErrorExecute, message); } #endregion }