public void MultiHost_TwoActiveAndOneIsDisposedStillTracksTelemetry()
        {
            var inclusionList = new[] { "Test.A" }.ToList();

            var dl1 = new TelemetryDiagnosticSourceListener(this.configuration, inclusionList);

            dl1.Subscribe();

            using (var listener = new DiagnosticListener("Test.A"))
                using (var dl2 = new TelemetryDiagnosticSourceListener(this.configuration, inclusionList))
                {
                    dl2.Subscribe();

                    Activity activity = new Activity("Test.A.Client.Monitoring");
                    listener.StartActivity(activity, null);
                    listener.StopActivity(activity, null);

                    Assert.AreEqual(1, this.sentItems.Count(t => t is DependencyTelemetry));

                    dl1.Dispose();

                    activity = new Activity("Test.A.Client.Monitoring");
                    listener.StartActivity(activity, null);
                    listener.StopActivity(activity, null);

                    Assert.AreEqual(2, this.sentItems.Count(t => t is DependencyTelemetry));
                }
        }
        public void MultiHost_OneListnerThenAnotherTracksTelemetry()
        {
            var inclusionList = new[] { "Test.A" }.ToList();

            using (var listener = new DiagnosticListener("Test.A"))
            {
                using (var dl = new TelemetryDiagnosticSourceListener(this.configuration, inclusionList))
                {
                    dl.Subscribe();

                    Activity activity = new Activity("Test.A.Client.Monitoring");
                    listener.StartActivity(activity, null);
                    listener.StopActivity(activity, null);

                    Assert.AreEqual(1, this.sentItems.Count(t => t is DependencyTelemetry));
                }

                using (var dl = new TelemetryDiagnosticSourceListener(this.configuration, inclusionList))
                {
                    dl.Subscribe();

                    Activity activity = new Activity("Test.A.Client.Monitoring");
                    listener.StartActivity(activity, null);
                    listener.StopActivity(activity, null);

                    Assert.AreEqual(2, this.sentItems.Count(t => t is DependencyTelemetry));
                }
            }
        }
        public static Activity?StartMessageDeserialize()
        {
            Activity?activity = null;

            if (_diagnostic.IsEnabled() && _diagnostic.IsEnabled(MessageDeserializeEvent))
            {
                activity = new Activity(MessageDeserializeEvent);
                _diagnostic.StartActivity(activity, null);
            }

            return(activity);
        }
        public void TelemetryDiagnosticSourceListenerIgnoresNotIncludedActivities()
        {
            var inclusionList = new[] { "Test.A:Test.A.Client.Monitoring" }.ToList();

            using (var listener = new DiagnosticListener("Test.A"))
                using (var dl = new TelemetryDiagnosticSourceListener(this.configuration, inclusionList))
                {
                    dl.Subscribe();

                    // Diagnostic Source is not ignored
                    Assert.IsTrue(listener.IsEnabled(), "There is a subscriber for diagnostic source");

                    // Activity1 is ignored per exclusion
                    Activity activity1 = new Activity("Test.A.Activity1");
                    Assert.IsFalse(listener.IsEnabled(activity1.OperationName), "There are no subscribers for activity 1");

                    int sentCountBefore = this.sentItems.Count;

                    listener.StartActivity(activity1, null);
                    Assert.AreEqual(sentCountBefore, this.sentItems.Count, "No telemetry item should be sent on activity 1 start");

                    listener.StopActivity(activity1, null);
                    Assert.AreEqual(sentCountBefore, this.sentItems.Count, "No telemetry item should be sent on activity 1 stop");

                    // Activity2 is ignored per exclusion
                    Activity activity2 = new Activity("Test.A.Activity2");
                    Assert.IsFalse(listener.IsEnabled(activity2.OperationName), "There are no subscribers for activity 2");

                    listener.StartActivity(activity2, null);
                    Assert.AreEqual(sentCountBefore, this.sentItems.Count, "No telemetry item should be sent on activity 2 start");

                    listener.StopActivity(activity2, null);
                    Assert.AreEqual(sentCountBefore, this.sentItems.Count, "No telemetry item should be sent on activity 2 stop");

                    // non-excluded activity from same diagnostic source is captured
                    Activity activity = new Activity("Test.A.Client.Monitoring");
                    Assert.IsTrue(listener.IsEnabled(activity.OperationName), "There is a subscriber for activity");

                    listener.StartActivity(activity, null);
                    Assert.AreEqual(sentCountBefore, this.sentItems.Count, "No telemetry item should be sent on activity start");

                    listener.StopActivity(activity, null);
                    Assert.AreEqual(sentCountBefore + 1, this.sentItems.Count, "One new telemetry item should be sent on activity stop");

                    DependencyTelemetry telemetryItem = this.sentItems.Last() as DependencyTelemetry;
                    Assert.IsNotNull(telemetryItem, "Dependency telemetry item should be sent");
                    Assert.AreEqual(telemetryItem.Name, activity.OperationName);
                }
        }
        private async ValueTask ProcessAsync(HttpMessage message, ReadOnlyMemory <HttpPipelinePolicy> pipeline, bool async)
        {
            var activity = new Activity("Azure.Core.Http.Request");

            activity.AddTag("http.method", message.Request.Method.Method);
            activity.AddTag("http.url", message.Request.Uri.ToString());
            activity.AddTag("requestId", message.Request.ClientRequestId);
            activity.AddTag("kind", "client");

            if (_resourceProviderNamespace != null)
            {
                activity.AddTag("az.namespace", _resourceProviderNamespace);
            }

            if (message.Request.Headers.TryGetValue("User-Agent", out string?userAgent))
            {
                activity.AddTag("http.user_agent", userAgent);
            }

            var diagnosticSourceActivityEnabled = s_diagnosticSource.IsEnabled(activity.OperationName, message);

            if (diagnosticSourceActivityEnabled)
            {
                s_diagnosticSource.StartActivity(activity, message);
            }
            else
            {
                activity.Start();
            }

            try
            {
                if (async)
                {
                    await ProcessNextAsync(message, pipeline, true).ConfigureAwait(false);
                }
                else
                {
                    ProcessNextAsync(message, pipeline, false).EnsureCompleted();
                }

                activity.AddTag("http.status_code", message.Response.Status.ToString(CultureInfo.InvariantCulture));
                activity.AddTag("serviceRequestId", message.Response.Headers.RequestId);
                if (message.ResponseClassifier.IsErrorResponse(message))
                {
                    activity.AddTag("otel.status_code", "ERROR");
                }
            }
            finally
            {
                if (diagnosticSourceActivityEnabled)
                {
                    s_diagnosticSource.StopActivity(activity, message);
                }
                else
                {
                    activity.Stop();
                }
            }
        }
        private T TrackOperation <T>(
            DiagnosticListener listener,
            string activityName,
            string parentId  = null,
            Action operation = null) where T : OperationTelemetry
        {
            Activity activity        = null;
            int      itemCountBefore = this.sentItems.Count;

            if (listener.IsEnabled(activityName))
            {
                activity = new Activity(activityName);

                if (Activity.Current == null && parentId != null)
                {
                    activity.SetParentId(parentId);
                }

                listener.StartActivity(activity, null);
            }

            operation?.Invoke();

            if (activity != null)
            {
                listener.StopActivity(activity, null);

                // a single new telemetry item was addedAssert.AreEqual(itemCountBefore + 1, this.sentItems.Count);
                return(this.sentItems.Last() as T);
            }

            // no new telemetry items were added
            Assert.AreEqual(itemCountBefore, this.sentItems.Count);
            return(null);
        }
Exemple #7
0
        public void TelemetryDiagnosticSourceListenerCapturesAllActivitiesByDefault()
        {
            var inclusionList = new[] { "Test.A" }.ToList();
            using (var dl = new TelemetryDiagnosticSourceListener(this.configuration, inclusionList))
            {
                dl.Subscribe();
                DiagnosticListener listener = new DiagnosticListener("Test.A");
                Activity activity = new Activity("Test.A.Client.Monitoring");

                Assert.IsTrue(listener.IsEnabled(), "There is a subscriber for a new diagnostic source");
                Assert.IsTrue(listener.IsEnabled(activity.OperationName), "There is a subscriber for a new activity");
                Assert.IsTrue(
                    listener.IsEnabled(
                        activity.OperationName + TelemetryDiagnosticSourceListener.ActivityStopNameSuffix),
                    "There is a subscriber for new activity Stop event");
                Assert.IsFalse(
                    listener.IsEnabled(activity.OperationName +
                                       TelemetryDiagnosticSourceListener.ActivityStartNameSuffix),
                    "There are no subscribers for new activity Start event");

                int sentCountBefore = this.sentItems.Count;

                listener.StartActivity(activity, null);
                Assert.AreEqual(sentCountBefore, this.sentItems.Count, "No telemetry item should be sent on activity start");

                listener.StopActivity(activity, null);
                Assert.AreEqual(sentCountBefore + 1, this.sentItems.Count, "One new telemetry item should be sent on activity stop");

                DependencyTelemetry telemetryItem = this.sentItems.Last() as DependencyTelemetry;
                Assert.IsNotNull(telemetryItem, "Dependency telemetry item should be sent");
                Assert.AreEqual(activity.OperationName, telemetryItem.Name);
            }
        }
        public void AzureClientSpansAreCollectedClientKind()
        {
            using (var listener = new DiagnosticListener("Azure.SomeClient"))
                using (var module = new DependencyTrackingTelemetryModule())
                {
                    module.Initialize(this.configuration);

                    Activity sendActivity = new Activity("Azure.SomeClient.Send");
                    sendActivity.AddTag("kind", "client");

                    listener.StartActivity(sendActivity, null);
                    listener.StopActivity(sendActivity, null);

                    var telemetry = this.sentItems.Last() as DependencyTelemetry;

                    Assert.IsNotNull(telemetry);
                    Assert.AreEqual("SomeClient.Send", telemetry.Name);
                    Assert.AreEqual(string.Empty, telemetry.Type);
                    Assert.IsTrue(telemetry.Success.Value);

                    Assert.IsNull(telemetry.Context.Operation.ParentId);
                    Assert.AreEqual(sendActivity.TraceId.ToHexString(), telemetry.Context.Operation.Id);
                    Assert.AreEqual(sendActivity.SpanId.ToHexString(), telemetry.Id);
                }
        }
Exemple #9
0
        private Activity StartActivity(IGrainCallContext callContext, IDictionary <string, object> requestContext)
        {
            var activity = new Activity(DiagnosticsLoggingStrings.GrainRequestIn);

            if (requestContext.TryGetValue(DiagnosticsLoggingStrings.RequestIdHeaderName, out object requestId))
            {
                activity.SetParentId((string)requestId);

                // We expect baggage to be empty by default
                // Only very advanced users will be using it in near future, we encourage them to keep baggage small (few items)

                if (requestContext.TryGetValue(DiagnosticsLoggingStrings.CorrelationContextHeaderName, out object baggage))
                {
                    KeyValuePair <string, string>[] values = (KeyValuePair <string, string>[])baggage;

                    foreach (var item in values)
                    {
                        activity.AddBaggage(item.Key, item.Value);
                    }
                }
            }

            if (_listener.IsEnabled(DiagnosticsLoggingStrings.GrainRequestInStartName))
            {
                _listener.StartActivity(activity, new { RequestContext = requestContext, CallContext = callContext });
            }
            else
            {
                // always start activity
                activity.Start();
            }

            return(activity);
        }
        public void AzureClientSpansAreCollectedForHttpException()
        {
            using (var listener = new DiagnosticListener("Azure.SomeClient"))
                using (var module = new DependencyTrackingTelemetryModule())
                {
                    module.Initialize(this.configuration);

                    var      exception    = new InvalidOperationException();
                    Activity httpActivity = new Activity("Azure.SomeClient.Http.Request")
                                            .AddTag("http.method", "PATCH")
                                            .AddTag("http.url", "http://host/path?query#fragment");

                    listener.StartActivity(httpActivity, null);
                    listener.Write("Azure.SomeClient.Send.Exception", exception);

                    listener.StopActivity(httpActivity, null);

                    var telemetry = this.sentItems.Last() as DependencyTelemetry;

                    Assert.IsNotNull(telemetry);
                    Assert.AreEqual("PATCH /path", telemetry.Name);
                    Assert.AreEqual("host", telemetry.Target);
                    Assert.AreEqual("http://host/path?query#fragment", telemetry.Data);
                    Assert.IsNull(telemetry.ResultCode);
                    Assert.AreEqual("Http", telemetry.Type);
                    Assert.IsFalse(telemetry.Success.Value);
                    Assert.AreEqual(exception.ToInvariantString(), telemetry.Properties["Error"]);

                    Assert.IsNull(telemetry.Context.Operation.ParentId);
                    Assert.AreEqual(httpActivity.TraceId.ToHexString(), telemetry.Context.Operation.Id);
                    Assert.AreEqual(httpActivity.SpanId.ToHexString(), telemetry.Id);
                }
        }
Exemple #11
0
        private T TrackOperation <T>(DiagnosticListener listener, string activityName, TaskStatus status) where T : OperationTelemetry
        {
            Activity activity = null;

            if (listener.IsEnabled(activityName))
            {
                activity = new Activity(activityName);
                activity.AddTag("MessageId", "messageId");
                if (listener.IsEnabled(activityName + ".Start"))
                {
                    listener.StartActivity(activity, new { Entity = "queueName", Endpoint = new Uri("sb://queuename.myservicebus.com/") });
                }
                else
                {
                    activity.Start();
                }
            }

            if (activity != null)
            {
                listener.StopActivity(activity, new { Entity = "queueName", Endpoint = new Uri("sb://queuename.myservicebus.com/"), Status = status });
                return(this.sentItems.Last() as T);
            }

            return(null);
        }
Exemple #12
0
            public async ValueTask <HttpResponseMessage> ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                var activity = (Activity)null;

                if (_listener.IsEnabled())
                {
                    activity = new Activity(request.RequestUri.AbsoluteUri);
                }


                if (activity != null)
                {
                    _listener.StartActivity(activity, request);
                }

                var response = await _handler.ProcessRequest(request, cancellationToken);

                if (activity != null)
                {
                    _listener.StopActivity(activity, response);
                }


                return(response);
            }
 public void Start()
 {
     if (_activity != null && _source.IsEnabled(_name))
     {
         _source.StartActivity(_activity, null);
     }
 }
        private Activity StartActivity(HttpContext httpContext)
        {
            var activity = new Activity(ActivityName);

            if (httpContext.Request.Headers.TryGetValue(RequestIdHeaderName, out var requestId))
            {
                activity.SetParentId(requestId);

                // We expect baggage to be empty by default
                // Only very advanced users will be using it in near future, we encouradge them to keep baggage small (few items)
                string[] baggage = httpContext.Request.Headers.GetCommaSeparatedValues(CorrelationContextHeaderName);
                if (baggage != StringValues.Empty)
                {
                    foreach (var item in baggage)
                    {
                        if (NameValueHeaderValue.TryParse(item, out var baggageItem))
                        {
                            activity.AddBaggage(baggageItem.Name.ToString(), baggageItem.Value.ToString());
                        }
                    }
                }
            }

            if (_diagnosticListener.IsEnabled(ActivityStartKey))
            {
                _diagnosticListener.StartActivity(activity, new { HttpContext = httpContext });
            }
            else
            {
                activity.Start();
            }

            return(activity);
        }
        public void AzureClientSpansAreCollectedForEventHubsException()
        {
            using (var listener = new DiagnosticListener("Azure.SomeClient"))
                using (var module = new DependencyTrackingTelemetryModule())
                {
                    module.Initialize(this.configuration);

                    Activity sendActivity = new Activity("Azure.SomeClient.Send")
                                            .AddTag("peer.address", "amqps://eventHub.servicebus.windows.net/")
                                            .AddTag("message_bus.destination", "queueName")
                                            .AddTag("kind", "producer")
                                            .AddTag("component", "eventhubs");

                    listener.StartActivity(sendActivity, null);
                    listener.StopActivity(sendActivity, null);

                    var telemetry = this.sentItems.Last() as DependencyTelemetry;

                    Assert.IsNotNull(telemetry);
                    Assert.AreEqual("SomeClient.Send", telemetry.Name);
                    Assert.AreEqual("amqps://eventHub.servicebus.windows.net/ | queueName", telemetry.Target);
                    Assert.AreEqual(string.Empty, telemetry.Data);
                    Assert.AreEqual(string.Empty, telemetry.ResultCode);
                    Assert.AreEqual("Azure Event Hubs", telemetry.Type);
                    Assert.IsTrue(telemetry.Success.Value);

                    Assert.IsNull(telemetry.Context.Operation.ParentId);
                    Assert.AreEqual(sendActivity.TraceId.ToHexString(), telemetry.Context.Operation.Id);
                    Assert.AreEqual(sendActivity.SpanId.ToHexString(), telemetry.Id);
                }
        }
        public void AzureClientSpansAreCollectedForHttpNotSuccessResponse()
        {
            using (var listener = new DiagnosticListener("Azure.SomeClient"))
                using (var module = new DependencyTrackingTelemetryModule())
                {
                    module.Initialize(this.configuration);

                    Activity httpActivity = new Activity("Azure.SomeClient.Http.Request")
                                            .AddTag("http.method", "PATCH")
                                            .AddTag("http.url", "http://host/path?query#fragment");

                    var payload = new HttpRequestMessage();
                    listener.StartActivity(httpActivity, payload);
                    httpActivity.AddTag("http.status_code", "503");

                    listener.StopActivity(httpActivity, payload);

                    var telemetry = this.sentItems.Last() as DependencyTelemetry;

                    Assert.IsNotNull(telemetry);
                    Assert.AreEqual("PATCH /path", telemetry.Name);
                    Assert.AreEqual("host", telemetry.Target);
                    Assert.AreEqual("http://host/path?query#fragment", telemetry.Data);
                    Assert.AreEqual("503", telemetry.ResultCode);
                    Assert.AreEqual("Http", telemetry.Type);
                    Assert.IsFalse(telemetry.Success.Value);

                    Assert.IsNull(telemetry.Context.Operation.ParentId);
                    Assert.AreEqual(httpActivity.TraceId.ToHexString(), telemetry.Context.Operation.Id);
                    Assert.AreEqual(httpActivity.SpanId.ToHexString(), telemetry.Id);
                }
        }
        public async Task <TResponse> Handle(TRequest request,
                                             CancellationToken cancellationToken,
                                             RequestHandlerDelegate <TResponse> next)
        {
            _logger.LogInformation(
                "Handling {MediatRRequest} with request={MediatRRequestData} and response={MediatRResponseData}",
                nameof(OTelMediatRTracingBehavior <TRequest, TResponse>), typeof(TRequest).Name, typeof(TResponse).Name);

            using var activityListener = new DiagnosticListener(OTelMediatROptions.OTelMediatRName);

            if (!activityListener.IsEnabled() || !activityListener.IsEnabled(OTelMediatROptions.OTelMediatRName))
            {
                return(await next());
            }

            var activity = new Activity($"{OTelMediatROptions.OTelMediatRName}.Execute")
                           .SetIdFormat(ActivityIdFormat.W3C);

            activityListener.StartActivity(activity, request);

            try
            {
                return(await next());
            }
            finally
            {
                if (activity != null)
                {
                    activityListener.StopActivity(activity, request);
                }
            }
        }
        public void AzureClientSpansAreCollectedLinks()
        {
            using (var listener = new DiagnosticListener("Azure.SomeClient"))
                using (var module = new DependencyTrackingTelemetryModule())
                {
                    module.Initialize(this.configuration);

                    var sendActivity = new Activity("Azure.SomeClient.Send");
                    var link0TraceId = "70545f717a9aa6a490d820438b9d2bf6";
                    var link1TraceId = "c5aa06717eef0c4592af26323ade92f7";
                    var link0SpanId  = "8b0b2fb40c84e64a";
                    var link1SpanId  = "3a69ce690411bb4f";

                    var payload = new PayloadWithLinks
                    {
                        Links = new List <Activity>
                        {
                            new Activity("link0").SetParentId($"00-{link0TraceId}-{link0SpanId}-01"),
                            new Activity("link1").SetParentId($"00-{link1TraceId}-{link1SpanId}-01"),
                        },
                    };

                    listener.StartActivity(sendActivity, payload);
                    listener.StopActivity(sendActivity, null);

                    var telemetry = this.sentItems.Last() as DependencyTelemetry;

                    Assert.IsNotNull(telemetry);
                    Assert.AreEqual("SomeClient.Send", telemetry.Name);
                    Assert.IsTrue(telemetry.Success.Value);

                    Assert.IsNull(telemetry.Context.Operation.ParentId);
                    Assert.AreEqual(sendActivity.TraceId.ToHexString(), telemetry.Context.Operation.Id);
                    Assert.AreEqual(sendActivity.SpanId.ToHexString(), telemetry.Id);

                    // does not throw
                    var jsonSettingThrowOnError = new JsonSerializerSettings
                    {
                        MissingMemberHandling = MissingMemberHandling.Error,
                        ReferenceLoopHandling = ReferenceLoopHandling.Error,
                        NullValueHandling     = NullValueHandling.Include,
                        DefaultValueHandling  = DefaultValueHandling.Include,
                    };

                    Assert.IsTrue(telemetry.Properties.TryGetValue("_MS.links", out var linksStr));
                    var actualLinks = JsonConvert.DeserializeObject <ApplicationInsightsLink[]>(linksStr, jsonSettingThrowOnError);

                    Assert.IsNotNull(actualLinks);
                    Assert.AreEqual(2, actualLinks.Length);

                    Assert.AreEqual(link0TraceId, actualLinks[0].OperationId);
                    Assert.AreEqual(link1TraceId, actualLinks[1].OperationId);

                    Assert.AreEqual(link0SpanId, actualLinks[0].Id);
                    Assert.AreEqual(link1SpanId, actualLinks[1].Id);

                    Assert.AreEqual($"[{{\"operation_Id\":\"{link0TraceId}\",\"id\":\"{link0SpanId}\"}},{{\"operation_Id\":\"{link1TraceId}\",\"id\":\"{link1SpanId}\"}}]", linksStr);
                }
        }
Exemple #19
0
        public Activity BeginQuery(IQueryContext context)
        {
            var payload = new
            {
                context
            };

            if (_source.IsEnabled(DiagnosticNames.Query, payload))
            {
                var activity = new Activity(DiagnosticNames.Query);

                _source.StartActivity(activity, payload);

                return(activity);
            }

            return(null);
        }
Exemple #20
0
        internal static Activity StartSendActivity(string clientId, EventHubsConnectionStringBuilder csb, string activePartitionRouting, IEnumerable <EventData> eventDatas, int count)
        {
            // skip if diagnostic source not enabled
            if (!DiagnosticListener.IsEnabled())
            {
                return(null);
            }

            // skip if no listeners for this "Send" activity
            if (!DiagnosticListener.IsEnabled(SendActivityName, csb.Endpoint, csb.EntityPath))
            {
                return(null);
            }

            Activity activity = new Activity(SendActivityName);

            activity.AddTag("peer.hostname", csb.Endpoint.Host);
            activity.AddTag("eh.event_hub_name", csb.EntityPath);
            activity.AddTag("eh.active_partition_routing", activePartitionRouting);
            activity.AddTag("eh.event_count", count.ToString());
            activity.AddTag("eh.client_id", clientId);

            // in many cases activity start event is not interesting,
            // in that case start activity without firing event
            if (DiagnosticListener.IsEnabled(SendActivityStartName))
            {
                DiagnosticListener.StartActivity(activity,
                                                 new
                {
                    csb.Endpoint,
                    Entity = csb.EntityPath,
                    ActivePartitionRouting = activePartitionRouting,
                    EventDatas             = eventDatas.Select(TransformEvent)
                });
            }
            else
            {
                activity.Start();
            }

            Inject(eventDatas);

            return(activity);
        }
Exemple #21
0
        private T TrackOperation <T>(DiagnosticListener listener, string activityName, TaskStatus status, string parentId = null) where T : OperationTelemetry
        {
            Activity activity        = null;
            int      itemCountBefore = this.sentItems.Count;

            if (listener.IsEnabled(activityName))
            {
                activity = new Activity(activityName);
                activity.AddTag("peer.hostname", "eventhubname.servicebus.windows.net");
                activity.AddTag("eh.event_hub_name", "ehname");
                activity.AddTag("eh.partition_key", "SomePartitionKeyHere");
                activity.AddTag("eh.client_id", "EventHubClient1(ehname)");

                if (Activity.Current == null && parentId != null)
                {
                    activity.SetParentId(parentId);
                }

                if (listener.IsEnabled(activityName + ".Start"))
                {
                    listener.StartActivity(
                        activity,
                        new
                    {
                        Entity       = "ehname",
                        Endpoint     = new Uri("sb://eventhubname.servicebus.windows.net/"),
                        PartitionKey = "SomePartitionKeyHere"
                    });
                }
                else
                {
                    activity.Start();
                }
            }

            if (activity != null)
            {
                listener.StopActivity(
                    activity,
                    new
                {
                    Entity       = "ehname",
                    Endpoint     = new Uri("sb://eventhubname.servicebus.windows.net/"),
                    PartitionKey = "SomePartitionKeyHere",
                    Status       = status
                });

                // a single new telemetry item was added
                Assert.AreEqual(itemCountBefore + 1, this.sentItems.Count);
                return(this.sentItems.Last() as T);
            }

            // no new telemetry items were added
            Assert.AreEqual(itemCountBefore, this.sentItems.Count);
            return(null);
        }
Exemple #22
0
        public void OnNext_RequestObserverd_OutgoingHttpRequestStopEventReceived()
        {
            // Arrange
            var counterMock = new Mock <Collector <Counter.Child> >(MockBehavior.Loose,
                                                                    "the_counter", "counter_help", new string[] { "host", "method", "endpoint", "status" }, true);
            var summaryMock = Metrics.CreateSummary(TestContext.TestName + "summary", "test_summary_help",
                                                    new SummaryConfiguration
            {
                LabelNames           = new string[] { "host", "method", "endpoint", "status" },
                SuppressInitialValue = true
            });

            var observer = new HttpHandlerDiagnosticListenerObserver(
                new HttpHandlerObserverConfig(),
                counterMock.Object, summaryMock);

            var listener = new DiagnosticListener("TestListener");

            listener.Subscribe(observer);

            var request = new HttpRequestMessage
            {
                Method     = new HttpMethod("GET"),
                RequestUri = new Uri("http://test/api/elements")
            };

            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                RequestMessage = request
            };


            // Act
            var activity = new Activity("System.Net.Http.HttpRequestOut");

            listener.StartActivity(activity, new
            {
                Request = request
            });
            listener.StopActivity(activity, new
            {
                Request  = request,
                Response = response
            });

            // Assert
            var counterMetrics = counterMock.Object.Collect();
            var summaryMetrics = summaryMock.Collect();

            Assert.AreEqual(1, counterMetrics.First().metric.Count);
            Assert.AreEqual(1, counterMetrics.First().metric[0].counter.value);
            Assert.AreEqual(1, summaryMetrics.First().metric.Count);
            Assert.IsNotNull(summaryMetrics.First().metric[0].summary);
        }
        public async Task <IActionResult> Index()
        {
            using var span =
                      DiagListener.StartActivity(new Activity(nameof(AirlineController) + "." + nameof(Index)), null);
            var bucket = await _travelSample.GetBucketAsync().ConfigureAwait(false);

            var queryResults = await bucket.Cluster
                               .QueryAsync <dynamic>("SELECT icao, name FROM `travel-sample` WHERE type = 'airline' ORDER BY name")
                               .ConfigureAwait(false);

            var results = new List <(string icao, string name)>();

            await foreach (var qr in queryResults.Rows)
            {
                results.Add((qr.icao, qr.name));
            }

            DiagListener.StopActivity(span, null);
            return(View(results));
        }
Exemple #24
0
        public static Activity?CreateAndStartActivity(this DiagnosticListener listener, string name)
        {
            if (!listener.IsEnabled(name))
            {
                return(null);
            }

            Activity activity = new Activity(name);

            return(listener.StartActivity(activity, null));
        }
Exemple #25
0
        private Activity Start(string operationName, Func <object> getPayload)
        {
            Activity activity     = null;
            string   activityName = BaseActivityName + operationName;

            if (DiagnosticListener.IsEnabled(activityName, this.entityPath))
            {
                activity = new Activity(activityName);
                if (DiagnosticListener.IsEnabled(activityName + ".Start"))
                {
                    DiagnosticListener.StartActivity(activity, getPayload());
                }
                else
                {
                    activity.Start();
                }
            }

            return(activity);
        }
        public void OnNext_RequestObserver_With_Null_Action_Value_And_Null_Controller_Value()
        {
            // Arrange
            var observer = new AspNetCoreDiagnosticListenerObserver();

            var registry = new DefaultCollectorRegistry();
            var factory  = Metrics.WithCustomRegistry(registry);

            var listener = new DiagnosticListener("TestListener2");

            listener.Subscribe(observer);



            var context = new DefaultHttpContext();

            context.Request.Method      = "GET";
            context.Request.Path        = new PathString("/api/test2");
            context.Response.StatusCode = 200;

            var httpConnectionFeature = new HttpConnectionFeature
            {
                ConnectionId = "12345"
            };

            context.Features.Set <IHttpConnectionFeature>(httpConnectionFeature);

            var routeData = new RouteData();

            routeData.Values.Add("controller", null);
            routeData.Values.Add("action", null);

            // Act
            var activity = new Activity("Microsoft.AspNetCore.Hosting.HttpRequestIn");

            listener.StartActivity(activity, new { HttpContext = context });
            listener.Write("Microsoft.AspNetCore.Mvc.AfterAction", new { httpContext = context, routeData });
            listener.StopActivity(activity, new { HttpContext = context });


            // Assert
            var requestCounter = (Counter)observer.GetType().GetField("_requestCounter",
                                                                      BindingFlags.Instance | BindingFlags.NonPublic).GetValue(observer);
            var requestSummary = (Summary)observer.GetType().GetField("_requestSummary",
                                                                      BindingFlags.Instance | BindingFlags.NonPublic).GetValue(observer);

            var counterMetrics = requestCounter.Collect();
            var summaryMetrics = requestSummary.Collect();



            Assert.IsTrue(counterMetrics.First().metric.Any(p => p.label[1].value == "/api/test2"));
            Assert.IsNotNull(summaryMetrics.First().metric[0].summary);
        }
Exemple #27
0
        private static async Task ProcessAsync(HttpPipelineMessage message, ReadOnlyMemory <HttpPipelinePolicy> pipeline, bool isAsync)
        {
            if (!s_diagnosticSource.IsEnabled())
            {
                await ProcessNextAsync(message, pipeline, isAsync).ConfigureAwait(false);

                return;
            }

            var activity = new Activity("Azure.Core.Http.Request");

            activity.AddTag("http.method", message.Request.Method.Method);
            activity.AddTag("http.url", message.Request.UriBuilder.ToString());
            activity.AddTag("requestId", message.Request.ClientRequestId);

            if (message.Request.Headers.TryGetValue("User-Agent", out string?userAgent))
            {
                activity.AddTag("http.user_agent", userAgent);
            }

            var diagnosticSourceActivityEnabled = s_diagnosticSource.IsEnabled(activity.OperationName, message);

            if (diagnosticSourceActivityEnabled)
            {
                s_diagnosticSource.StartActivity(activity, message);
            }
            else
            {
                activity.Start();
            }


            if (isAsync)
            {
                await ProcessNextAsync(message, pipeline, true).ConfigureAwait(false);
            }
            else
            {
                ProcessNextAsync(message, pipeline, false).EnsureCompleted();
            }

            activity.AddTag("http.status_code", message.Response.Status.ToString(CultureInfo.InvariantCulture));
            activity.AddTag("serviceRequestId", message.Response.Headers.RequestId);

            if (diagnosticSourceActivityEnabled)
            {
                s_diagnosticSource.StopActivity(activity, message);
            }
            else
            {
                activity.Stop();
            }
        }
        public void OnNext_RequestObserved_RequestStopEventReceived()
        {
            // Arrange
            var observer = new AspNetCoreDiagnosticListenerObserver();
            var listener = new DiagnosticListener("TestListener");

            listener.Subscribe(observer);

            var context = new DefaultHttpContext();

            context.Request.Method      = "GET";
            context.Request.Path        = new PathString("/api/test");
            context.Response.StatusCode = 200;

            var httpConnectionFeature = new HttpConnectionFeature
            {
                ConnectionId = "1234"
            };

            context.Features.Set <IHttpConnectionFeature>(httpConnectionFeature);

            var routeData = new RouteData();

            routeData.Values.Add("controller", "test");
            routeData.Values.Add("action", "get");
            // Act

            // Create the activity, start it and immediately stop it. This will
            // cause the OnNext method in the observer to be called with the events
            // Microsoft.AspNetCore.Hosting.HttpRequestIn.Start and
            // Microsoft.AspNetCore.Hosting.HttpRequestIn.Stop. In addition,
            // Activity.Current will be managed by the listener.
            var activity = new Activity("Microsoft.AspNetCore.Hosting.HttpRequestIn");

            listener.StartActivity(activity, new { HttpContext = context });
            listener.Write("Microsoft.AspNetCore.Mvc.AfterAction", new { httpContext = context, routeData });
            listener.StopActivity(activity, new { HttpContext = context });


            // Assert
            var requestCounter = (Counter)observer.GetType().GetField("_requestCounter",
                                                                      BindingFlags.Instance | BindingFlags.NonPublic).GetValue(observer);
            var requestSummary = (Summary)observer.GetType().GetField("_requestSummary",
                                                                      BindingFlags.Instance | BindingFlags.NonPublic).GetValue(observer);

            var counterMetrics = requestCounter.Collect();
            var summaryMetrics = requestSummary.Collect();

            Assert.AreEqual(1, counterMetrics.First().metric.Count);
            Assert.AreEqual(1, counterMetrics.First().metric[0].counter.value);
            Assert.AreEqual(1, summaryMetrics.First().metric.Count);
            Assert.IsNotNull(summaryMetrics.First().metric[0].summary);
        }
 public void BaselineActivityWithDiagListener()
 {
     if (s_listener.IsEnabled())
     {
         if (s_listener.IsEnabled("MyActivity"))
         {
             Activity a = new Activity("MyActivity");
             s_listener.StartActivity(a, null);
             s_listener.StopActivity(a, null);
         }
     }
 }
Exemple #30
0
        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
        {
            var result = context.Object as ExecutionResult;

            if (result == null)
            {
                throw new FormatException();
            }

            if (!result.TryExportToDataTable(_entityType, out var dataTable))
            {
                throw new FormatException();
            }


            var csvExportActivity = new Activity("XlsxGeneration");

            if (DiagnosticListener.IsEnabled(DiagnosticListenerName))
            {
                DiagnosticListener.StartActivity(csvExportActivity, new { context });
            }

            var response = context.HttpContext.Response;

            response.Headers.Add("Content-Disposition", $"attachment; filename=\"{_entityType}.xlsx\"");

            using (var memoryStream = new MemoryStream())
            {
                using (var workbook = new XLWorkbook())
                {
                    var worksheet = workbook.Worksheets.Add(_entityType);
                    var rowIndex  = 1;
                    foreach (var record in result.GetRecordsStream(_entityType, true))
                    {
                        var cellIndex = 1;
                        foreach (var field in record)
                        {
                            worksheet.Cell(rowIndex, cellIndex).Value = field;
                            cellIndex++;
                        }
                        rowIndex++;
                    }

                    workbook.SaveAs(memoryStream);
                    memoryStream.WriteTo(response.Body);
                }
            }

            if (DiagnosticListener.IsEnabled(DiagnosticListenerName))
            {
                DiagnosticListener.StopActivity(csvExportActivity, null);
            }
        }