Beispiel #1
0
        public VocabTermTests(ITestOutputHelper output)
        {
            this.output = output;
            _listener = new DiagnosticListener("Testing");
            _listener.Subscribe(new ConsoleLogger(this.output));
            JsonStreamingParser.DiagSource = _listener;

        }
Beispiel #2
0
        public async Task Should_start_activity_and_set_appropriate_headers()
        {
            // Generate an id we can use for the request id header (in the correct format)

            var      diagnosticListener = new DiagnosticListener("DummySource");
            Activity started            = null;

            diagnosticListener.Subscribe(new CallbackDiagnosticListener(pair =>
            {
                if (pair.Key == $"{ActivityNames.OutgoingPhysicalMessage}.Start")
                {
                    started = Activity.Current;
                }
            }));

            var context = new TestableOutgoingPhysicalMessageContext();

            var behavior = new OutgoingPhysicalMessageDiagnostics(diagnosticListener);

            var activity = new Activity("Outer")
            {
                TraceStateString = "TraceStateValue",
            };

            activity.AddBaggage("Key1", "Value1");
            activity.AddBaggage("Key2", "Value2");
            activity.Start();

            await behavior.Invoke(context, () => Task.CompletedTask);

            activity.Stop();

            started.ShouldNotBeNull();
            started.ParentId.ShouldBe(activity.Id);

            context.Headers.ShouldContain(kvp => kvp.Key == "traceparent" && kvp.Value == started.Id);
            context.Headers.ShouldContain(kvp => kvp.Key == "tracestate" && kvp.Value == activity.TraceStateString);
            context.Headers.ShouldContain(kvp => kvp.Key == "Correlation-Context" && kvp.Value == "Key2=Value2,Key1=Value1");
        }
Beispiel #3
0
        public void ActivityStopDoesNotFireIfNoListenerAttachedForStart()
        {
            // Arrange
            var diagnosticListener = new DiagnosticListener("DummySource");
            var logger             = new LoggerWithScopes(isEnabled: true);
            var hostingApplication = CreateApplication(out var features, diagnosticListener: diagnosticListener, logger: logger);
            var startFired         = false;
            var stopFired          = false;

            diagnosticListener.Subscribe(new CallbackDiagnosticListener(pair =>
            {
                // This should not fire
                if (pair.Key == "Microsoft.AspNetCore.Hosting.HttpRequestIn.Start")
                {
                    startFired = true;
                }

                // This should not fire
                if (pair.Key == "Microsoft.AspNetCore.Hosting.HttpRequestIn.Stop")
                {
                    stopFired = true;
                }
            }),
                                         (s, o, arg3) =>
            {
                // The events are off
                return(false);
            });


            // Act
            var context = hostingApplication.CreateContext(features);

            hostingApplication.DisposeContext(context, exception: null);

            Assert.False(startFired);
            Assert.False(stopFired);
            Assert.Null(Activity.Current);
        }
        public void InitializeSetsTelemetryOperationNameToControllerAndActionAndParameterFromActionContext()
        {
            var actionContext = new ActionContext();

            actionContext.RouteData = new RouteData();
            actionContext.RouteData.Values.Add("controller", "account");
            actionContext.RouteData.Values.Add("action", "login");
            actionContext.RouteData.Values.Add("parameter", "myName");

            var contextAccessor = HttpContextAccessorHelper.CreateHttpContextAccessor(new RequestTelemetry(), actionContext);

            var telemetryListener = new DiagnosticListener(TestListenerName);
            var initializer       = new MvcDiagnosticsListener();

            telemetryListener.Subscribe(initializer);
            telemetryListener.Write("Microsoft.AspNetCore.Mvc.BeforeAction",
                                    new { httpContext = contextAccessor.HttpContext, routeData = actionContext.RouteData });

            var telemetry = contextAccessor.HttpContext.Features.Get <RequestTelemetry>();

            Assert.Equal("GET account/login [parameter]", telemetry.Name);
        }
Beispiel #5
0
        public async Task Should_not_fire_activity_start_stop_when_no_listener_attached()
        {
            var diagnosticListener = new DiagnosticListener("DummySource");
            var context            = new TestableIncomingLogicalMessageContext();
            var processedFired     = false;

            diagnosticListener.Subscribe(new CallbackDiagnosticListener(pair =>
            {
                // This should not fire
                if (pair.Key == $"{ActivityNames.IncomingLogicalMessage}.Processed")
                {
                    processedFired = true;
                }
            }),
                                         (s, o, arg3) => false);

            var behavior = new IncomingLogicalMessageDiagnostics(diagnosticListener);

            await behavior.Invoke(context, () => Task.CompletedTask);

            processedFired.ShouldBeFalse();
        }
        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);

            using (var listener = CreateHostingListener(false))
            {
                telemetryListener.Subscribe(listener);
                telemetryListener.Write("Microsoft.AspNetCore.Mvc.BeforeAction",
                                        new { httpContext = contextAccessor.HttpContext, routeData = actionContext.RouteData });
            }
            var telemetry = contextAccessor.HttpContext.Features.Get <RequestTelemetry>();

            Assert.Equal("GET account/login", telemetry.Name);
        }
        public void ActivityIsAvailableDuringUnhandledExceptionCall()
        {
            var diagnosticListener = new DiagnosticListener("DummySource");
            var hostingApplication = CreateApplication(out var features, diagnosticListener: diagnosticListener);

            bool endCalled = false;

            diagnosticListener.Subscribe(new CallbackDiagnosticListener(pair =>
            {
                if (pair.Key == "Microsoft.AspNetCore.Hosting.UnhandledException")
                {
                    endCalled = true;
                    Assert.NotNull(Activity.Current);
                    Assert.Equal("Microsoft.AspNetCore.Hosting.HttpRequestIn", Activity.Current.OperationName);
                }
            }));

            var context = hostingApplication.CreateContext(features);

            hostingApplication.DisposeContext(context, new Exception());
            Assert.True(endCalled);
        }
        public void ActivityIsCreatedAndLogged()
        {
            var diagnosticListener = new DiagnosticListener("DummySource");
            var hostingApplication = CreateApplication(out var features, diagnosticListener: diagnosticListener);

            bool startCalled = false;

            diagnosticListener.Subscribe(new CallbackDiagnosticListener(pair =>
            {
                if (pair.Key == "Microsoft.AspNetCore.Hosting.HttpRequestIn.Start")
                {
                    startCalled = true;
                    Assert.NotNull(pair.Value);
                    Assert.NotNull(Activity.Current);
                    Assert.Equal("Microsoft.AspNetCore.Hosting.HttpRequestIn", Activity.Current.OperationName);
                    AssertProperty <HttpContext>(pair.Value, "HttpContext");
                }
            }));

            hostingApplication.CreateContext(features);
            Assert.NotNull(Activity.Current);
            Assert.True(startCalled);
        }
Beispiel #9
0
        public void DiagnosticSourceStartStop()
        {
            using (DiagnosticListener listener = new DiagnosticListener("Testing"))
            {
                DiagnosticSource source = listener;
                var observer            = new TestObserver();

                using (listener.Subscribe(observer))
                {
                    var arguments = new { args = "arguments" };

                    var activity = new Activity("activity");

                    // Test Activity.Stop
                    source.StartActivity(activity, arguments);
                    Assert.Equal(activity.OperationName + ".Start", observer.EventName);
                    Assert.Equal(arguments, observer.EventObject);

                    Assert.NotNull(observer.Activity);
                    Assert.True(DateTime.UtcNow - new TimeSpan(0, 1, 0) <= observer.Activity.StartTimeUtc);
                    Assert.True(observer.Activity.StartTimeUtc <= DateTime.UtcNow);
                    Assert.True(observer.Activity.Duration == TimeSpan.Zero);

                    observer.Reset();

                    // Test Activity.Stop
                    source.StopActivity(activity, arguments);
                    Assert.Equal(activity.OperationName + ".Stop", observer.EventName);
                    Assert.Equal(arguments, observer.EventObject);

                    // Confirm that duration is set.
                    Assert.NotNull(observer.Activity);
                    Assert.True(TimeSpan.Zero < observer.Activity.Duration);
                    Assert.True(observer.Activity.StartTimeUtc + observer.Activity.Duration < DateTime.UtcNow);
                }
            }
        }
        public void BasicIsEnabled()
        {
            using (DiagnosticListener listener = new DiagnosticListener("TestingBasicIsEnabled"))
            {
                DiagnosticSource source = listener;
                var result = new List <KeyValuePair <string, object> >();

                bool seenUninteresting       = false;
                bool seenStructPayload       = false;
                Predicate <string> predicate = delegate(string name)
                {
                    if (name == "Uninteresting")
                    {
                        seenUninteresting = true;
                    }
                    if (name == "StructPayload")
                    {
                        seenStructPayload = true;
                    }

                    return(name == "StructPayload");
                };

                // Assert.False(listener.IsEnabled());  Since other things might turn on all DiagnosticSources, we can't ever test that it is not enabled.
                using (listener.Subscribe(new ObserverToList <TelemData>(result), predicate))
                {
                    Assert.False(source.IsEnabled("Uninteresting"));
                    Assert.False(source.IsEnabled("Uninteresting", "arg1", "arg2"));
                    Assert.True(source.IsEnabled("StructPayload"));
                    Assert.True(source.IsEnabled("StructPayload", "arg1", "arg2"));
                    Assert.True(seenUninteresting);
                    Assert.True(seenStructPayload);
                    Assert.True(listener.IsEnabled());
                }
            }
        }
        public void ParseCompleteSwagger()
        {
            DiagnosticListener listener = new DiagnosticListener("Testing");

            JsonStreamingParser.DiagSource = listener;
            listener.Subscribe(new ConsoleLogger(this.output));

            Vocabulary vocab = OpenApiVocab.Create();

            var stream = typeof(ParsingTests).Assembly
                         .GetManifestResourceStream(typeof(ParsingTests), "forecast.io.swagger.json");

            var swaggerDoc = new OpenApiDocument();

            JsonStreamingParser.ParseStream(stream, swaggerDoc, vocab);

            Assert.Equal("2.0", swaggerDoc.Version);
            Assert.Equal(1, swaggerDoc.Schemes.Count);
            Assert.Equal("https", swaggerDoc.Schemes.First());
            Assert.True(swaggerDoc.Paths.Count > 0);
            Assert.False(String.IsNullOrEmpty(swaggerDoc.Info.Description));
            Assert.False(String.IsNullOrEmpty(swaggerDoc.Info.Title));
            Assert.True(String.IsNullOrEmpty(swaggerDoc.Info.Version));
        }
        public void ActivityIsStoppedDuringUnhandledExceptionCall()
        {
            var diagnosticSource   = new DiagnosticListener("DummySource");
            var hostingApplication = CreateApplication(out var features, diagnosticSource: diagnosticSource);

            bool endCalled = false;

            diagnosticSource.Subscribe(new CallbackDiagnosticListener(pair =>
            {
                if (pair.Key == "Microsoft.AspNetCore.Hosting.HttpRequestIn.Stop")
                {
                    endCalled = true;
                    Assert.NotNull(Activity.Current);
                    Assert.True(Activity.Current.Duration > TimeSpan.Zero);
                    Assert.Equal("Microsoft.AspNetCore.Hosting.HttpRequestIn", Activity.Current.OperationName);
                    AssertProperty <HttpContext>(pair.Value, "HttpContext");
                }
            }));

            var context = hostingApplication.CreateContext(features);

            hostingApplication.DisposeContext(context, new Exception());
            Assert.True(endCalled);
        }
        protected override IDisposable Subscribe(DiagnosticListener listener, IDiagnosticProcessor target)
        {
            var adapter = new DiagnosticSourceAdapter(target, _loggerFactory);

            return(listener.Subscribe(adapter, adapter.IsEnabled));
        }
        public void MultiSubscriber()
        {
            using (DiagnosticListener listener = new DiagnosticListener("TestingMultiSubscriber"))
            {
                DiagnosticSource source = listener;
                var subscriber1Result   = new List <KeyValuePair <string, object> >();
                Predicate <string> subscriber1Predicate = name => (name == "DataForSubscriber1");
                var subscriber1Observer = new ObserverToList <TelemData>(subscriber1Result);

                var subscriber2Result = new List <KeyValuePair <string, object> >();
                Predicate <string> subscriber2Predicate = name => (name == "DataForSubscriber2");
                var subscriber2Observer = new ObserverToList <TelemData>(subscriber2Result);

                // Get two subscribers going.
                using (var subscription1 = listener.Subscribe(subscriber1Observer, subscriber1Predicate))
                {
                    using (var subscription2 = listener.Subscribe(subscriber2Observer, 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);
            }
        }
Beispiel #15
0
 public Task StartAsync(CancellationToken cancellationToken)
 {
     _diagnosticubscription = _diagnosticListener.Subscribe(this);
     return(Task.CompletedTask);
 }
Beispiel #16
0
 public void OnNext(DiagnosticListener value)
 {
     _listenersSubscriptions.Add(value.Subscribe(this));
 }
 public ActivityRequestTracer(ILoggerFactory loggerFactory, ClusterOptions options)
 {
     _loggerFactory      = loggerFactory;
     _diagnosticListener = new DiagnosticListener(RequestTracing.SourceName);
     _diagnosticListener.Subscribe(new ThresholdActivityObserver(loggerFactory, options.ThresholdOptions ?? new ThresholdOptions()));
 }
 public DiagnosticsActivity_Specs()
 {
     _store    = new List <KeyValuePair <string, object> >();
     _listener = new DiagnosticListener(GetType().FullName);
     _listener.Subscribe(new TestListener(_store));
 }
Beispiel #19
0
 public BadRequestEventListener(DiagnosticListener diagnosticListener, Action <KeyValuePair <string, object> > callback)
 {
     _subscription = diagnosticListener.Subscribe(this, IsEnabled);
     _callback     = callback;
 }
Beispiel #20
0
        public static IDisposable SubscribeWithAdapter(this DiagnosticListener diagnostic, object target, Predicate <string> isEnabled)
        {
            var adapter = new DiagnosticSourceAdapter(target);

            return(diagnostic.Subscribe(adapter, isEnabled));
        }