Пример #1
0
        public void TestActivityWithListenerNoActivityCreate()
        {
            RemoteExecutor.Invoke(() => {
                using (ActivitySource aSource = new ActivitySource("SourceActivityListener"))
                {
                    Assert.False(aSource.HasListeners());

                    using (ActivityListener listener = new ActivityListener
                    {
                        ActivityStarted = activity => Assert.NotNull(activity),
                        ActivityStopped = activity => Assert.NotNull(activity),
                        ShouldListenTo = (activitySource) => object.ReferenceEquals(aSource, activitySource),
                        GetRequestedDataUsingParentId = (ref ActivityCreationOptions <string> activityOptions) => ActivityDataRequest.None,
                        GetRequestedDataUsingContext = (ref ActivityCreationOptions <ActivityContext> activityOptions) => ActivityDataRequest.None
                    }
                           )
                    {
                        ActivitySource.AddActivityListener(listener);
                        Assert.True(aSource.HasListeners());

                        // The listener is not allowing to create a new Activity.
                        Assert.Null(aSource.StartActivity("nullActivity"));
                    }
                }
            }).Dispose();
        }
Пример #2
0
 private static bool IsEnabled()
 {
     // check if there is a parent Activity or if someone listens to "System.Net.Http" ActivitySource or "HttpHandlerDiagnosticListener" DiagnosticListener.
     return(Activity.Current != null ||
            s_activitySource.HasListeners() ||
            s_diagnosticListener.IsEnabled());
 }
Пример #3
0
        public void SdkSamplesAndProcessesLegacyActivityWithRightConfigOnWildCardMode()
        {
            bool samplerCalled = false;

            var sampler = new TestSampler
            {
                SamplingAction =
                    (samplingParameters) =>
                {
                    samplerCalled = true;
                    return(new SamplingResult(SamplingDecision.RecordAndSample));
                },
            };

            using TestActivityProcessor testActivityProcessor = new TestActivityProcessor();

            bool startCalled = false;
            bool endCalled   = false;

            testActivityProcessor.StartAction =
                (a) =>
            {
                Assert.True(samplerCalled);
                Assert.False(Sdk.SuppressInstrumentation);
                Assert.True(a.IsAllDataRequested);     // If Proccessor.OnStart is called, activity's IsAllDataRequested is set to true
                startCalled = true;
            };

            testActivityProcessor.EndAction =
                (a) =>
            {
                Assert.False(Sdk.SuppressInstrumentation);
                Assert.True(a.IsAllDataRequested);     // If Processor.OnEnd is called, activity's IsAllDataRequested is set to true
                endCalled = true;
            };

            var emptyActivitySource = new ActivitySource(string.Empty);

            Assert.False(emptyActivitySource.HasListeners()); // No ActivityListener for empty ActivitySource added yet

            var operationNameForLegacyActivity = "TestOperationName";

            // AddLegacyOperationName chained to TracerProviderBuilder
            using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                                       .SetSampler(sampler)
                                       .AddSource("ABCCompany.XYZProduct.*") // Adding a wild card source
                                       .AddProcessor(testActivityProcessor)
                                       .AddLegacySource(operationNameForLegacyActivity)
                                       .Build();

            Assert.True(emptyActivitySource.HasListeners()); // Listener for empty ActivitySource added after TracerProvider build

            Activity activity = new Activity(operationNameForLegacyActivity);

            activity.Start();
            activity.Stop();

            Assert.True(startCalled); // Processor.OnStart is called since we added a legacy OperationName
            Assert.True(endCalled);   // Processor.OnEnd is called since we added a legacy OperationName
        }
Пример #4
0
        public void TestActivityWithListenerActivityCreateAndAllDataRequested()
        {
            RemoteExecutor.Invoke(() => {
                using (ActivitySource aSource = new ActivitySource("SourceActivityListener"))
                {
                    int counter = 0;
                    Assert.False(aSource.HasListeners());

                    using (ActivityListener listener = new ActivityListener
                    {
                        ActivityStarted = activity => counter++,
                        ActivityStopped = activity => counter--,
                        ShouldListenTo = (activitySource) => object.ReferenceEquals(aSource, activitySource),
                        GetRequestedDataUsingParentId = (ref ActivityCreationOptions <string> activityOptions) => ActivityDataRequest.AllDataAndRecorded,
                        GetRequestedDataUsingContext = (ref ActivityCreationOptions <ActivityContext> activityOptions) => ActivityDataRequest.AllDataAndRecorded
                    }
                           )
                    {
                        ActivitySource.AddActivityListener(listener);

                        Assert.True(aSource.HasListeners());

                        using (Activity activity = aSource.StartActivity("AllDataRequestedActivity"))
                        {
                            Assert.NotNull(activity);
                            Assert.True(activity.IsAllDataRequested);
                            Assert.Equal(1, counter);

                            Assert.Equal(0, activity.Tags.Count());
                            Assert.Equal(0, activity.Baggage.Count());

                            Assert.True(object.ReferenceEquals(activity, activity.AddTag("key", "value")));
                            Assert.True(object.ReferenceEquals(activity, activity.AddBaggage("key", "value")));

                            Assert.Equal(1, activity.Tags.Count());
                            Assert.Equal(1, activity.Baggage.Count());

                            using (Activity activity1 = aSource.StartActivity("AllDataRequestedActivity1"))
                            {
                                Assert.NotNull(activity1);
                                Assert.True(activity1.IsAllDataRequested);
                                Assert.Equal(2, counter);

                                Assert.Equal(0, activity1.Links.Count());
                                Assert.Equal(0, activity1.Events.Count());
                                Assert.True(object.ReferenceEquals(activity1, activity1.AddEvent(new ActivityEvent("e1"))));
                                Assert.Equal(1, activity1.Events.Count());
                            }
                            Assert.Equal(1, counter);
                        }

                        Assert.Equal(0, counter);
                    }
                }
            }).Dispose();
        }
        public void AddLegacyOperationNameAddsActivityListenerForEmptyActivitySource()
        {
            var emptyActivitySource = new ActivitySource(string.Empty);
            var builder             = Sdk.CreateTracerProviderBuilder();

            builder.AddLegacySource("TestOperationName");

            Assert.False(emptyActivitySource.HasListeners());
            using var provider = builder.Build();
            Assert.True(emptyActivitySource.HasListeners());
        }
Пример #6
0
        public void SdkProcessesLegacyActivityWhenActivitySourceIsUpdatedWithAddSource()
        {
            using TestActivityProcessor testActivityProcessor = new TestActivityProcessor();

            bool startCalled = false;
            bool endCalled   = false;

            testActivityProcessor.StartAction =
                (a) =>
            {
                Assert.False(Sdk.SuppressInstrumentation);
                Assert.True(a.IsAllDataRequested);     // If Proccessor.OnStart is called, activity's IsAllDataRequested is set to true
                startCalled = true;
            };

            testActivityProcessor.EndAction =
                (a) =>
            {
                Assert.False(Sdk.SuppressInstrumentation);
                Assert.True(a.IsAllDataRequested);     // If Processor.OnEnd is called, activity's IsAllDataRequested is set to true
                endCalled = true;
            };

            var emptyActivitySource = new ActivitySource(string.Empty);

            Assert.False(emptyActivitySource.HasListeners()); // No ActivityListener for empty ActivitySource added yet

            var operationNameForLegacyActivity = "TestOperationName";
            var activitySourceForLegacyActvity = new ActivitySource("TestActivitySource", "1.0.0");

            // AddLegacyOperationName chained to TracerProviderBuilder
            using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                                       .AddSource(activitySourceForLegacyActvity.Name) // Add the updated ActivitySource as a Source
                                       .AddLegacySource(operationNameForLegacyActivity)
                                       .AddProcessor(testActivityProcessor)
                                       .Build();

            Assert.True(emptyActivitySource.HasListeners()); // Listener for empty ActivitySource added after TracerProvider build

            Activity activity = new Activity(operationNameForLegacyActivity);

            activity.Start();
            ActivityInstrumentationHelper.SetActivitySourceProperty(activity, activitySourceForLegacyActvity);
            activity.Stop();

            Assert.True(startCalled); // Processor.OnStart is called since we provided the legacy OperationName
            Assert.True(endCalled);   // Processor.OnEnd is not called since the ActivitySource is updated and the updated source name is added as a Source to the provider
        }
Пример #7
0
        public void TraceEnter(
            string methodInfo,
            Tuple <string, string>[] configParameters,
            string[] paramNames,
            object[] paramValues)
        {
            if (ActivityTracer.HasListeners())
            {
                var activity = ActivityTracer.StartActivity($"{this.name}{methodInfo}");

                if (ShouldIncludeArguments(configParameters))
                {
                    for (int paramIndex = 0; paramIndex < paramNames.Length; paramIndex++)
                    {
                        // Prepending Arguments. because Jaeger alphabetizes the tags, so it was hard to discover them
                        string paramName  = "arguments." + paramNames[paramIndex];
                        object paramValue = paramValues[paramIndex];
                        // TODO: Support other forms of serialization
                        string serializedParamValue = paramValue?.ToString();

                        // TODO: This supports 'object' directly, could remove serialization at this level, depends how well documented adding serialization at any other level is
                        activity.AddTag(paramName, serializedParamValue);
                    }
                }
            }
        }
Пример #8
0
        public void SdkDoesNotProcessLegacyActivityWithNoAdditionalConfig()
        {
            using TestActivityProcessor testActivityProcessor = new TestActivityProcessor();

            bool startCalled = false;
            bool endCalled   = false;

            testActivityProcessor.StartAction =
                (a) =>
            {
                Assert.False(Sdk.SuppressInstrumentation);
                Assert.True(a.IsAllDataRequested);     // If Proccessor.OnStart is called, activity's IsAllDataRequested is set to true
                startCalled = true;
            };

            testActivityProcessor.EndAction =
                (a) =>
            {
                Assert.False(Sdk.SuppressInstrumentation);
                Assert.True(a.IsAllDataRequested);     // If Processor.OnEnd is called, activity's IsAllDataRequested is set to true
                endCalled = true;
            };

            var emptyActivitySource = new ActivitySource(string.Empty);

            Assert.False(emptyActivitySource.HasListeners()); // No ActivityListener for empty ActivitySource added yet

            // No AddLegacyOperationName chained to TracerProviderBuilder
            using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                                       .AddProcessor(testActivityProcessor)
                                       .Build();

            Assert.False(emptyActivitySource.HasListeners()); // No listener for empty ActivitySource even after build

            Activity activity = new Activity("Test");

            activity.Start();
            activity.Stop();

            Assert.False(startCalled); // Processor.OnStart is not called since we did not add any legacy OperationName
            Assert.False(endCalled);   // Processor.OnEnd is not called since we did not add any legacy OperationName
        }
        public void TestActivityWithListenerNoActivityCreate()
        {
            RemoteExecutor.Invoke(() => {
                using ActivitySource aSource = new ActivitySource("SourceActivityListener");
                Assert.False(aSource.HasListeners());

                using ActivityListener listener = new ActivityListener();
                listener.ActivityStarted        = activity => Assert.NotNull(activity);
                listener.ActivityStopped        = activity => Assert.NotNull(activity);
                listener.ShouldListenTo         = (activitySource) => object.ReferenceEquals(aSource, activitySource);
                listener.SampleUsingParentId    = (ref ActivityCreationOptions <string> activityOptions) => ActivitySamplingResult.None;
                listener.Sample = (ref ActivityCreationOptions <ActivityContext> activityOptions) => ActivitySamplingResult.None;

                ActivitySource.AddActivityListener(listener);
                Assert.True(aSource.HasListeners());

                // The listener is not allowing to create a new Activity.
                Assert.Null(aSource.StartActivity("nullActivity"));
            }).Dispose();
        }
        public void AddLegacyOperationName_NullBuilder_Noop()
        {
            TracerProviderBuilder builder = null;

            // No exception is thrown on executing this line
            builder.AddLegacySource("TestOperationName");
            using var provider = builder.Build();

            var emptyActivitySource = new ActivitySource(string.Empty);

            Assert.False(emptyActivitySource.HasListeners()); // Check if AddLegacyOperationName was noop after TracerProviderBuilder.Build
        }
        public void BeginRequest(HttpContext httpContext, HostingApplication.Context context)
        {
            long startTimestamp = 0;

            if (HostingEventSource.Log.IsEnabled())
            {
                context.EventLogEnabled = true;
                // To keep the hot path short we defer logging in this function to non-inlines
                RecordRequestStartEventLog(httpContext);
            }

            var diagnosticListenerEnabled = _diagnosticListener.IsEnabled();
            var diagnosticListenerActivityCreationEnabled = (diagnosticListenerEnabled && _diagnosticListener.IsEnabled(ActivityName, httpContext));
            var loggingEnabled = _logger.IsEnabled(LogLevel.Critical);


            if (loggingEnabled || diagnosticListenerActivityCreationEnabled || _activitySource.HasListeners())
            {
                context.Activity = StartActivity(httpContext, loggingEnabled, diagnosticListenerActivityCreationEnabled, out var hasDiagnosticListener);
                context.HasDiagnosticListener = hasDiagnosticListener;
            }

            if (diagnosticListenerEnabled)
            {
                if (_diagnosticListener.IsEnabled(DeprecatedDiagnosticsBeginRequestKey))
                {
                    startTimestamp = Stopwatch.GetTimestamp();
                    RecordBeginRequestDiagnostics(httpContext, startTimestamp);
                }
            }

            // To avoid allocation, return a null scope if the logger is not on at least to some degree.
            if (loggingEnabled)
            {
                // Scope may be relevant for a different level of logging, so we always create it
                // see: https://github.com/aspnet/Hosting/pull/944
                // Scope can be null if logging is not on.
                context.Scope = _logger.RequestScope(httpContext);

                if (_logger.IsEnabled(LogLevel.Information))
                {
                    if (startTimestamp == 0)
                    {
                        startTimestamp = Stopwatch.GetTimestamp();
                    }

                    // Non-inline
                    LogRequestStarting(context);
                }
            }
            context.StartTimestamp = startTimestamp;
        }
Пример #12
0
        public void TestConstruction()
        {
            RemoteExecutor.Invoke(() => {
                using ActivitySource as1 = new ActivitySource("Source1");
                Assert.Equal("Source1", as1.Name);
                Assert.Equal(String.Empty, as1.Version);
                Assert.False(as1.HasListeners());

                using ActivitySource as2 = new ActivitySource("Source2", "1.1.1.2");
                Assert.Equal("Source2", as2.Name);
                Assert.Equal("1.1.1.2", as2.Version);
                Assert.False(as2.HasListeners());
            }).Dispose();
        }
            public Task <MotorCloudEvent <string> > ConvertMessageAsync(MotorCloudEvent <string> dataCloudEvent,
                                                                        CancellationToken token = default)
            {
                _logger.LogInformation("log your request");
                var tmpChar = dataCloudEvent.TypedData.ToCharArray();

                if (!ActivitySource.HasListeners())
                {
                    throw new ArgumentException();
                }
                var reversed = tmpChar.Reverse().ToArray();

                _summary.WithLabels("collect_your_metrics").Observe(1.0);
                return(Task.FromResult(dataCloudEvent.CreateNew(new string(reversed))));
            }
Пример #14
0
        public void TestStartActivityWithNoListener()
        {
            RemoteExecutor.Invoke(() => {
                using ActivitySource aSource = new ActivitySource("SourceActivity");
                Assert.Equal("SourceActivity", aSource.Name);
                Assert.Equal(string.Empty, aSource.Version);
                Assert.False(aSource.HasListeners());

                Activity current = Activity.Current;

                // no listeners, we should get null activity.
                using Activity a1 = aSource.StartActivity("a1");
                Assert.Null(a1);
                Assert.Equal(Activity.Current, current);
            }).Dispose();
        }
Пример #15
0
        public static Activity?StartWithTraceId(
            this ActivitySource activitySource,
            string name,
            ActivityKind activityKind,
            string?traceId,
            string?traceState)
        {
            if (!activitySource.HasListeners())
            {
                return(null);
            }

            if (traceId != null && ActivityContext.TryParse(traceId, traceState, out ActivityContext context))
            {
                return(activitySource.StartActivity(name, activityKind, context));
            }

            return(activitySource.StartActivity(name, activityKind));
        }
        private static void ProcessRequest(HttpWebRequest request)
        {
            if (!WebRequestActivitySource.HasListeners() || IsRequestInstrumented(request))
            {
                // No subscribers to the ActivitySource or this request was instrumented by previous
                // ProcessRequest, such is the case with redirect responses where the same request is sent again.
                return;
            }

            var activity = WebRequestActivitySource.StartActivity(ActivityName, ActivityKind.Client);

            if (activity == null)
            {
                // There is a listener but it decided not to sample the current request.
                return;
            }

            IAsyncResult asyncContext = writeAResultAccessor(request);

            if (asyncContext != null)
            {
                // Flow here is for [Begin]GetRequestStream[Async].

                AsyncCallbackWrapper callback = new AsyncCallbackWrapper(request, activity, asyncCallbackAccessor(asyncContext));
                asyncCallbackModifier(asyncContext, callback.AsyncCallback);
            }
            else
            {
                // Flow here is for [Begin]GetResponse[Async] without a prior call to [Begin]GetRequestStream[Async].

                asyncContext = readAResultAccessor(request);
                AsyncCallbackWrapper callback = new AsyncCallbackWrapper(request, activity, asyncCallbackAccessor(asyncContext));
                asyncCallbackModifier(asyncContext, callback.AsyncCallback);
            }

            AddRequestTagsAndInstrumentRequest(request, activity);
        }
Пример #17
0
 internal static Activity?CreateStartedActivity(this ActivitySource source, string activityName, Dictionary <string, string>?tags = null)
 {
     if (!source.HasListeners())
     {
         return(default);