public static void StopMessageDeserialize(Activity?activity)
 {
     if (activity != null)
     {
         _diagnostic.StopActivity(activity, null);
     }
 }
        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));
                }
            }
        }
Exemple #4
0
 internal void SendStop(Activity activity, TaskStatus?status)
 {
     if (activity != null)
     {
         DiagnosticListener.StopActivity(activity, new
         {
             Entity = this.entityPath,
             Status = status ?? TaskStatus.Faulted
         });
     }
 }
        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);
                }
        }
        public void EndParsing(Activity activity, IQueryContext context)
        {
            if (activity != null)
            {
                var payload = new
                {
                    context
                };

                if (_source.IsEnabled(DiagnosticNames.Parsing, payload))
                {
                    _source.StopActivity(activity, payload);
                }
            }
        }
        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);
                }
        }
        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);
                }
        }
Exemple #9
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 #10
0
        public void EndQuery(Activity activity, IQueryContext context)
        {
            if (activity != null)
            {
                var payload = new
                {
                    context,
                    result = context.Result
                };

                if (_source.IsEnabled(DiagnosticNames.Query, payload))
                {
                    _source.StopActivity(activity, payload);
                }
            }
        }
Exemple #11
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);
            }
        }
        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();
                }
            }
        }
Exemple #13
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);
            }
        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);
        }
        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 #16
0
 internal void _stop(Activity activity, Func <object> getPayload)
 {
     if (activity != null)
     {
         _source.StopActivity(activity, getPayload());
     }
 }
Exemple #17
0
 public static void StopActivityIfExist(this DiagnosticListener listener, Activity?activity)
 {
     if (activity != null)
     {
         listener.StopActivity(activity, null);
     }
 }
        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 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);
                }
        }
 internal void WriteStopped(Activity?activity, DateTimeOffset endTimeUtc, IJobExecutionContext context)
 {
     if (activity != null && diagnosticListener.IsEnabled(name))
     {
         activity.SetEndTime(endTimeUtc.UtcDateTime);
         diagnosticListener.StopActivity(activity, context);
     }
 }
Exemple #22
0
        internal static void StopSendActivity(Activity activity, EventHubsConnectionStringBuilder csb, string activePartitionRouting, IEnumerable <EventData> eventDatas, Task sendTask)
        {
            if (activity == null)
            {
                return;
            }

            DiagnosticListener.StopActivity(activity,
                                            new
            {
                csb.Endpoint,
                Entity = csb.EntityPath,
                ActivePartitionRouting = activePartitionRouting,
                EventDatas             = eventDatas.Select(TransformEvent),
                sendTask?.Status
            });
        }
        internal static void StopSendActivity(Activity activity, EventHubsConnectionStringBuilder csb, string partitionKey, IEnumerable <EventData> eventDatas, Task sendTask)
        {
            if (activity == null)
            {
                return;
            }

            DiagnosticListener.StopActivity(activity,
                                            new
            {
                csb.Endpoint,
                Entity       = csb.EntityPath,
                PartitionKey = partitionKey,
                EventDatas   = eventDatas,
                sendTask?.Status
            });
        }
        /// <summary>
        /// Stops the activity and notifies listeners about it.
        /// </summary>
        /// <param name="activity">Activity to stop.</param>
        /// <param name="contextItems">HttpContext.Items.</param>
        /// <returns>True if activity was found in the stack, false otherwise.</returns>
        public static bool StopAspNetActivity(Activity activity, IDictionary contextItems)
        {
            var currentActivity = Activity.Current;

            if (activity != null && currentActivity != null)
            {
                // silently stop all child activities before activity
                int iteration = 0;
                while (currentActivity != activity)
                {
                    currentActivity.Stop();
                    var newCurrentActivity = Activity.Current;

                    if (newCurrentActivity == null)
                    {
                        return(false);
                    }

                    // there could be a case when request or any child activity is stopped
                    // from the child execution context. In this case, Activity is present in the Current Stack,
                    // but is finished, i.e. stopping it has no effect on the Current.
                    if (newCurrentActivity == currentActivity)
                    {
                        // We could not reach our 'activity' in the stack and have to report 'lost activity'
                        // if child activity is broken, we can still stop the root one that we own to clean up
                        // all resources
                        AspNetTelemetryCorrelationEventSource.Log.FinishedActivityIsDetected(currentActivity.Id, currentActivity.OperationName);
                        activity.Stop();
                        return(false);
                    }

                    // We also protect from endless loop with the MaxActivityStackSize
                    // in case it would ever be possible to have cycles in the Activity stack.
                    if (iteration++ == MaxActivityStackSize)
                    {
                        // this is for internal error reporting
                        AspNetTelemetryCorrelationEventSource.Log.ActivityStackIsTooDeepError();

                        // this is for debugging
                        AspNetTelemetryCorrelationEventSource.Log.ActivityStackIsTooDeepDetails(currentActivity.Id, currentActivity.OperationName);
                        activity.Stop();
                        return(false);
                    }

                    currentActivity = newCurrentActivity;
                }

                // if activity is in the stack, stop it with Stop event
                AspNetListener.StopActivity(currentActivity, new { });
                contextItems[ActivityKey] = null;

                AspNetTelemetryCorrelationEventSource.Log.ActivityStopped(currentActivity.Id, currentActivity.OperationName);
                return(true);
            }

            return(false);
        }
Exemple #25
0
        private void EndRequest(IOwinContext context, Activity activity, Exception exception = null)
        {
            if (exception != null)
            {
                context.Set("Steeltoe.Owin.Exception", exception);
            }

            _listener.StopActivity(activity, new { OwinContext = context });
        }
Exemple #26
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 #27
0
        public void Dispose()
        {
            if (Activity == null)
            {
                return;
            }

            PropagateTagsUpwards();
            _diagListener.StopActivity(Activity, this);
        }
 private void StopActivity(HttpContext httpContext, Activity activity, bool hasDiagnosticListener)
 {
     if (hasDiagnosticListener)
     {
         _diagnosticListener.StopActivity(activity, new { HttpContext = httpContext });
     }
     else
     {
         activity.Stop();
     }
 }
        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 #30
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);
        }