示例#1
0
        internal static object RunWithActivity(string host, int port)
        {
            // Enable OpenTelemetry for the sources "Samples.SampleServer" and "Samples.SampleClient"
            // and use the Jaeger exporter.
            using var openTelemetry = OpenTelemetrySdk.EnableOpenTelemetry(
                      builder => builder
                      .AddActivitySource("Samples.SampleServer")
                      .AddActivitySource("Samples.SampleClient")
                      .UseJaegerExporter(o =>
            {
                o.ServiceName = "jaeger-test";
                o.AgentHost   = host;
                o.AgentPort   = port;
            }));

            // The above lines are required only in Applications
            // which decide to use OT.

            using (var sample = new InstrumentationWithActivitySource())
            {
                sample.Start();

                Console.WriteLine("Traces are being created and exported" +
                                  "to Jaeger in the background. Use Jaeger to view them." +
                                  "Press ENTER to stop.");
                Console.ReadLine();
            }

            return(null);
        }
示例#2
0
        internal static object Run(string zipkinUri)
        {
            // Enable OpenTelemetry for the sources "Samples.SampleServer" and "Samples.SampleClient"
            // and use the Zipkin exporter.
            using var openTelemetry = OpenTelemetrySdk.EnableOpenTelemetry(
                      builder => builder
                      .AddActivitySource("Samples.SampleServer")
                      .AddActivitySource("Samples.SampleClient")
                      .UseZipkinExporter(o =>
            {
                o.ServiceName = "test-zipkin";
                o.Endpoint    = new Uri(zipkinUri);
            }));

            using (var sample = new InstrumentationWithActivitySource())
            {
                sample.Start();

                System.Console.WriteLine("Traces are being created and exported" +
                                         "to Zipkin in the background. Use Zipkin to view them." +
                                         "Press ENTER to stop.");
                System.Console.ReadLine();
            }

            return(null);
        }
示例#3
0
        public async Task HttpDependenciesInstrumentationInjectsHeadersAsync()
        {
            var spanProcessor = new Mock <ActivityProcessor>();
            var request       = new HttpRequestMessage
            {
                RequestUri = new Uri(this.url),
                Method     = new HttpMethod("GET"),
            };

            var parent = new Activity("parent")
                         .SetIdFormat(ActivityIdFormat.W3C)
                         .Start();

            parent.TraceStateString   = "k1=v1,k2=v2";
            parent.ActivityTraceFlags = ActivityTraceFlags.Recorded;

            using (OpenTelemetrySdk.EnableOpenTelemetry(
                       (builder) => builder.AddHttpClientDependencyInstrumentation()
                       .SetProcessorPipeline(p => p.AddProcessor(n => spanProcessor.Object))))
            {
                using var c = new HttpClient();
                await c.SendAsync(request);
            }

            Assert.Equal(2, spanProcessor.Invocations.Count); // begin and end was called
            var span = (Activity)spanProcessor.Invocations[1].Arguments[0];

            Assert.Equal(parent.TraceId, span.Context.TraceId);
            Assert.Equal(parent.SpanId, span.ParentSpanId);
            Assert.NotEqual(parent.SpanId, span.Context.SpanId);
            Assert.NotEqual(default, span.Context.SpanId);
        public void ExporterIsSlowerThanDelay()
        {
            var exportStartTimes = new List <long>();
            var exportEndTimes   = new List <long>();
            var activityExporter = new TestActivityExporter(_ =>
            {
                exportStartTimes.Add(Stopwatch.GetTimestamp());
                Thread.Sleep(50);
                exportEndTimes.Add(Stopwatch.GetTimestamp());
            });

            using var activityProcessor = new BatchingActivityProcessor(activityExporter, 128, TimeSpan.FromMilliseconds(30), DefaultTimeout, 10);
            using var openTelemetrySdk  = OpenTelemetrySdk.EnableOpenTelemetry(b => b
                                                                               .AddActivitySource(ActivitySourceName)
                                                                               .SetSampler(new AlwaysOnSampler())
                                                                               .AddProcessorPipeline(pp => pp.AddProcessor(ap => activityProcessor)));

            var activities = new List <Activity>();

            for (int i = 0; i < 20; i++)
            {
                activities.Add(this.CreateActivity(i.ToString()));
            }

            var exported = this.WaitForActivities(activityExporter, 20, TimeSpan.FromSeconds(2));

            Assert.Equal(activities.Count, exported.Length);
            Assert.InRange(exportStartTimes.Count, 2, 20);

            for (int i = 1; i < exportStartTimes.Count - 1; i++)
            {
                Assert.InRange(exportStartTimes[i], exportEndTimes[i - 1] + 1, exportStartTimes[i + 1] - 1);
            }
        }
        public async Task HttpDependenciesInstrumentationInjectsHeadersAsync()
        {
            var activityProcessor = new Mock <ActivityProcessor>();

            using var shutdownSignal = OpenTelemetrySdk.EnableOpenTelemetry(b =>
            {
                b.AddProcessorPipeline(c => c.AddProcessor(ap => activityProcessor.Object));
                b.AddHttpWebRequestDependencyInstrumentation();
            });

            var request = (HttpWebRequest)WebRequest.Create(this.url);

            request.Method = "GET";

            var parent = new Activity("parent")
                         .SetIdFormat(ActivityIdFormat.W3C)
                         .Start();

            parent.TraceStateString   = "k1=v1,k2=v2";
            parent.ActivityTraceFlags = ActivityTraceFlags.Recorded;

            using var response = await request.GetResponseAsync();

            Assert.Equal(2, activityProcessor.Invocations.Count); // begin and end was called
            var activity = (Activity)activityProcessor.Invocations[1].Arguments[0];

            Assert.Equal(parent.TraceId, activity.Context.TraceId);
            Assert.Equal(parent.SpanId, activity.ParentSpanId);
            Assert.NotEqual(parent.SpanId, activity.Context.SpanId);
            Assert.NotEqual(default, activity.Context.SpanId);
        public void AddActivityAfterQueueIsExhausted()
        {
            int exportCalledCount = 0;
            var activityExporter  = new TestActivityExporter(_ =>
            {
                Interlocked.Increment(ref exportCalledCount);
                Thread.Sleep(50);
            });

            using var activityProcessor = new BatchingActivityProcessor(activityExporter, 1, TimeSpan.FromMilliseconds(100), DefaultTimeout, 1);
            using var openTelemetrySdk  = OpenTelemetrySdk.EnableOpenTelemetry(b => b
                                                                               .AddActivitySource(ActivitySourceName)
                                                                               .SetSampler(new AlwaysOnSampler())
                                                                               .AddProcessorPipeline(pp => pp.AddProcessor(ap => activityProcessor)));

            var activities = new List <Activity>();

            for (int i = 0; i < 20; i++)
            {
                activities.Add(this.CreateActivity(i.ToString()));
            }

            var exported = this.WaitForActivities(activityExporter, 1, DefaultTimeout);

            Assert.Equal(1, exportCalledCount);
            Assert.InRange(exported.Length, 1, 2);
            Assert.Contains(activities.First(), exported);
        }
示例#7
0
 public OpenTelemetrySdkBenchmarksActivity()
 {
     // Not configuring pipeline, which will result in default NoOpActivityProcessor.
     var openTel = OpenTelemetrySdk.EnableOpenTelemetry(
         (builder) => builder.AddActivitySource("BenchMark")
         );
 }
        public void ExportNotSampledActivities()
        {
            int exportCalledCount = 0;
            var activityExporter  = new TestActivityExporter(_ => Interlocked.Increment(ref exportCalledCount));

            using var activityProcessor = new BatchingActivityProcessor(activityExporter, 128, DefaultDelay, DefaultTimeout, 1);
            using var openTelemetrySdk  = OpenTelemetrySdk.EnableOpenTelemetry(b => b
                                                                               .SetSampler(new ParentOrElseSampler(new AlwaysOffSampler()))
                                                                               .AddActivitySource(ActivitySourceName)
                                                                               .AddProcessorPipeline(pp => pp.AddProcessor(ap => activityProcessor)));

            var activity1 = this.CreateSampledEndedActivity(ActivityName1);
            var activity2 = this.CreateNotSampledEndedActivity(ActivityName2);

            // Activities are recorded and exported in the same order as they are created, we test that a non
            // sampled activity is not exported by creating and ending a sampled activity after a non sampled activity
            // and checking that the first exported activity is the sampled activity (the non sampled did not get
            // exported).
            var exported = this.WaitForActivities(activityExporter, 1, DefaultTimeout);

            Assert.Equal(1, exportCalledCount);

            // Need to check this because otherwise the variable activity1 is unused, other option is to not
            // have a activity1 variable.
            Assert.Single(exported);
            Assert.Contains(activity1, exported);
        }
        public async Task SuccessfulTemplateControllerCallGeneratesASpan()
        {
            var expectedResource = Resources.Resources.CreateServiceResource("test-service");
            var spanProcessor    = new Mock <ActivityProcessor>();

            void ConfigureTestServices(IServiceCollection services)
            {
                this.openTelemetrySdk = OpenTelemetrySdk.EnableOpenTelemetry(
                    (builder) => builder.AddRequestInstrumentation()
                    .SetResource(expectedResource)
                    .AddProcessorPipeline(p => p.AddProcessor(n => spanProcessor.Object)));
            }

            // Arrange
            using (var client = this.factory
                                .WithWebHostBuilder(builder =>
                                                    builder.ConfigureTestServices(ConfigureTestServices))
                                .CreateClient())
            {
                // Act
                var response = await client.GetAsync("/api/values");

                // Assert
                response.EnsureSuccessStatusCode(); // Status Code 200-299

                WaitForProcessorInvocations(spanProcessor, 2);
            }

            Assert.Equal(2, spanProcessor.Invocations.Count); // begin and end was called
            var span = (Activity)spanProcessor.Invocations[1].Arguments[0];

            Assert.Equal(ActivityKind.Server, span.Kind);
            Assert.Equal("/api/values", span.Tags.FirstOrDefault(i => i.Key == SpanAttributeConstants.HttpPathKey).Value);
            Assert.Equal(expectedResource, span.GetResource());
        }
示例#10
0
        internal static object Run(OpenTracingShimOptions options)
        {
            // Enable OpenTelemetry for the source "MyCompany.MyProduct.MyWebServer"
            // and use Console exporter.
            using var openTelemetry = OpenTelemetrySdk.EnableOpenTelemetry(
                      (builder) => builder.AddActivitySource("MyCompany.MyProduct.MyWebServer")
                      .SetResource(Resources.CreateServiceResource("MyServiceName"))
                      .UseConsoleExporter(opt => opt.DisplayAsJson = options.DisplayAsJson));

            // The above line is required only in applications
            // which decide to use OpenTelemetry.

            // Following shows how to use the OpenTracing shim

            var tracer = new TracerShim(TracerProvider.GetTracer("MyCompany.MyProduct.MyWebServer"), new TraceContextFormat());

            using (IScope parentScope = tracer.BuildSpan("Parent").StartActive(finishSpanOnDispose: true))
            {
                parentScope.Span.SetTag("my", "value");
                parentScope.Span.SetOperationName("parent span new name");

                // The child scope will automatically use parentScope as its parent.
                using (IScope childScope = tracer.BuildSpan("Child").StartActive(finishSpanOnDispose: true))
                {
                    childScope.Span.SetTag("Child Tag", "Child Tag Value").SetTag("ch", "value").SetTag("more", "attributes");
                }
            }

            System.Console.WriteLine("Press Enter key to exit.");

            return(null);
        }
        internal static object Run(OpenTelemetryShimOptions options)
        {
            // Enable OpenTelemetry for the source "MyCompany.MyProduct.MyWebServer"
            // and use a single pipeline with a custom MyProcessor, and Console exporter.
            using var openTelemetry = OpenTelemetrySdk.EnableOpenTelemetry(
                      (builder) => builder.AddActivitySource("MyCompany.MyProduct.MyWebServer")
                      .SetResource(Resources.CreateServiceResource("MyServiceName"))
                      .UseConsoleExporter(opt => opt.DisplayAsJson = options.DisplayAsJson));

            // The above line is required only in applications
            // which decide to use Open Telemetry.

            var tracer = TracerProvider.GetTracer("MyCompany.MyProduct.MyWebServer");
            var span   = tracer.StartSpan("parent span");

            span.SetAttribute("my", "value");
            span.UpdateName("parent span new name");

            var spanChild = tracer.StartSpan("child span");

            spanChild.AddEvent("sample event").SetAttribute("ch", "value").SetAttribute("more", "attributes");
            spanChild.End();

            span.End();

            System.Console.WriteLine("Press Enter key to exit.");

            return(null);
        }
示例#12
0
        public void ZPagesExporter_CustomActivityProcessor()
        {
            const string          ActivitySourceName    = "zpages.test";
            Guid                  requestId             = Guid.NewGuid();
            TestActivityProcessor testActivityProcessor = new TestActivityProcessor();

            bool startCalled = false;
            bool endCalled   = false;

            testActivityProcessor.StartAction =
                (a) =>
            {
                startCalled = true;
            };

            testActivityProcessor.EndAction =
                (a) =>
            {
                endCalled = true;
            };

            var openTelemetrySdk = OpenTelemetrySdk.EnableOpenTelemetry(b => b
                                                                        .AddActivitySource(ActivitySourceName)
                                                                        .UseZPagesExporter(
                                                                            processorConfigure: p => p.AddProcessor((next) => testActivityProcessor)));

            var source   = new ActivitySource(ActivitySourceName);
            var activity = source.StartActivity("Test Zipkin Activity");

            activity?.Stop();

            Assert.True(startCalled);
            Assert.True(endCalled);
        }
        public void GrpcClientCallsAreCollectedSuccessfully(string baseAddress)
        {
            var uri             = new Uri($"{baseAddress}:{this.fixture.Port}");
            var uriHostNameType = Uri.CheckHostName(uri.Host);

            var expectedResource = Resources.Resources.CreateServiceResource("test-service");
            var spanProcessor    = new Mock <ActivityProcessor>();

            var parent = new Activity("parent")
                         .Start();

            using (OpenTelemetrySdk.EnableOpenTelemetry(
                       (builder) => builder
                       .AddGrpcClientDependencyInstrumentation()
                       .SetResource(expectedResource)
                       .AddProcessorPipeline(p => p.AddProcessor(n => spanProcessor.Object))))
            {
                var channel = GrpcChannel.ForAddress(uri);
                var client  = new Greeter.GreeterClient(channel);
                var rs      = client.SayHello(new HelloRequest());
            }

            Assert.Equal(2, spanProcessor.Invocations.Count); // begin and end was called
            var span = (Activity)spanProcessor.Invocations[1].Arguments[0];

            Assert.Equal(parent.TraceId, span.Context.TraceId);
            Assert.Equal(parent.SpanId, span.ParentSpanId);
            Assert.NotEqual(parent.SpanId, span.Context.SpanId);
            Assert.NotEqual(default, span.Context.SpanId);
        public void ProcessorDoesNotBlockOnExporter()
        {
            var resetEvent       = new ManualResetEvent(false);
            var activityExporter = new TestActivityExporter(_ => resetEvent.WaitOne(TimeSpan.FromSeconds(10)));

            using var activityProcessor = new BatchingActivityProcessor(activityExporter, 128, DefaultDelay, DefaultTimeout, 128);

            using var openTelemetrySdk = OpenTelemetrySdk.EnableOpenTelemetry(b => b
                                                                              .AddActivitySource(ActivitySourceName)
                                                                              .SetSampler(new AlwaysOnSampler())
                                                                              .AddProcessorPipeline(pp => pp.AddProcessor(ap => activityProcessor)));

            var activity = Source.StartActivity("foo");

            // does not block
            var sw = Stopwatch.StartNew();

            activity?.Stop();
            sw.Stop();

            Assert.InRange(sw.Elapsed, TimeSpan.Zero, TimeSpan.FromMilliseconds(100));

            resetEvent.Set();

            var exported = this.WaitForActivities(activityExporter, 1, DefaultTimeout);

            Assert.Single(exported);
        }
示例#15
0
        public void UseJaegerExporterWithCustomActivityProcessor()
        {
            const string          ActivitySourceName    = "jaeger.test";
            TestActivityProcessor testActivityProcessor = new TestActivityProcessor();

            bool startCalled = false;
            bool endCalled   = false;

            testActivityProcessor.StartAction =
                (a) =>
            {
                startCalled = true;
            };

            testActivityProcessor.EndAction =
                (a) =>
            {
                endCalled = true;
            };

            var openTelemetrySdk = OpenTelemetrySdk.EnableOpenTelemetry(b => b
                                                                        .AddActivitySource(ActivitySourceName)
                                                                        .UseJaegerExporter(
                                                                            null, p => p.AddProcessor((next) => testActivityProcessor)));

            var source   = new ActivitySource(ActivitySourceName);
            var activity = source.StartActivity("Test Jaeger Activity");

            activity?.Stop();

            Assert.True(startCalled);
            Assert.True(endCalled);
        }
示例#16
0
        public void SqlClientErrorsAreCollectedSuccessfully(string beforeCommand, string errorCommand)
        {
            var activity      = new Activity("Current").AddBaggage("Stuff", "123");
            var spanProcessor = new Mock <ActivityProcessor>();

            using (OpenTelemetrySdk.EnableOpenTelemetry(
                       (builder) => builder.AddSqlClientDependencyInstrumentation()
                       .AddProcessorPipeline(p => p.AddProcessor(n => spanProcessor.Object))))
            {
                var operationId   = Guid.NewGuid();
                var sqlConnection = new SqlConnection(TestConnectionString);
                var sqlCommand    = sqlConnection.CreateCommand();
                sqlCommand.CommandText = "SP_GetOrders";
                sqlCommand.CommandType = CommandType.StoredProcedure;

                var beforeExecuteEventData = new
                {
                    OperationId = operationId,
                    Command     = sqlCommand,
                    Timestamp   = (long?)1000000L,
                };

                activity.Start();
                this.fakeSqlClientDiagnosticSource.Write(
                    beforeCommand,
                    beforeExecuteEventData);

                var commandErrorEventData = new
                {
                    OperationId = operationId,
                    Command     = sqlCommand,
                    Exception   = new Exception("Boom!"),
                    Timestamp   = 2000000L,
                };

                this.fakeSqlClientDiagnosticSource.Write(
                    errorCommand,
                    commandErrorEventData);

                activity.Stop();
            }

            Assert.Equal(2, spanProcessor.Invocations.Count); // begin and end was called

            var span = (Activity)spanProcessor.Invocations[0].Arguments[0];

            Assert.Equal("master", span.DisplayName);
            Assert.Equal(ActivityKind.Client, span.Kind);

            Assert.Equal("Unknown", span.Tags.FirstOrDefault(i => i.Key == SpanAttributeConstants.StatusCodeKey).Value);
            Assert.Equal("Boom!", span.Tags.FirstOrDefault(i => i.Key == SpanAttributeConstants.StatusDescriptionKey).Value);
            Assert.Equal("sql", span.Tags.FirstOrDefault(i => i.Key == SpanAttributeConstants.ComponentKey).Value);
            Assert.Equal("sql", span.Tags.FirstOrDefault(i => i.Key == SpanAttributeConstants.DatabaseTypeKey).Value);
            Assert.Equal("master", span.Tags.FirstOrDefault(i => i.Key == SpanAttributeConstants.DatabaseInstanceKey).Value);
            Assert.Equal("SP_GetOrders", span.Tags.FirstOrDefault(i => i.Key == SpanAttributeConstants.DatabaseStatementKey).Value);
            Assert.Equal("(localdb)\\MSSQLLocalDB", span.Tags.FirstOrDefault(i => i.Key == SpanAttributeConstants.PeerServiceKey).Value);
        }
 public SimpleActivityProcessorTest()
 {
     this.activityExporter = new TestActivityExporter(null);
     this.openTelemetry    = OpenTelemetrySdk.EnableOpenTelemetry(b => b
                                                                  .AddActivitySource(ActivitySourceName)
                                                                  .AddProcessorPipeline(p => p
                                                                                        .SetExporter(this.activityExporter)
                                                                                        .SetExportingProcessor(e => new SimpleActivityProcessor(e)))
                                                                  .SetSampler(new AlwaysOnActivitySampler()));
     this.activitySource = new ActivitySource(ActivitySourceName);
 }
示例#18
0
        public void GetStatusWithNoStatusInActivity()
        {
            using var openTelemetrySdk = OpenTelemetrySdk.EnableOpenTelemetry(b => b
                                                                              .AddActivitySource(ActivitySourceName));

            using var source   = new ActivitySource(ActivitySourceName);
            using var activity = source.StartActivity(ActivityName);
            activity?.Stop();

            Assert.False(activity.GetStatus().IsValid);
        }
示例#19
0
        public void SqlClientCallsAreCollectedSuccessfully(
            string beforeCommand,
            string afterCommand,
            CommandType commandType,
            string commandText,
            bool captureStoredProcedureCommandName,
            bool captureTextCommandContent)
        {
            using var sqlConnection = new SqlConnection(TestConnectionString);
            using var sqlCommand    = sqlConnection.CreateCommand();

            var spanProcessor = new Mock <ActivityProcessor>();

            using (OpenTelemetrySdk.EnableOpenTelemetry(
                       (builder) => builder.AddSqlClientDependencyInstrumentation(
                           (opt) =>
            {
                opt.SetTextCommandContent = captureTextCommandContent;
                opt.SetStoredProcedureCommandName = captureStoredProcedureCommandName;
            })
                       .AddProcessorPipeline(p => p.AddProcessor(n => spanProcessor.Object))))
            {
                var operationId = Guid.NewGuid();
                sqlCommand.CommandType = commandType;
                sqlCommand.CommandText = commandText;

                var beforeExecuteEventData = new
                {
                    OperationId = operationId,
                    Command     = sqlCommand,
                    Timestamp   = (long?)1000000L,
                };

                this.fakeSqlClientDiagnosticSource.Write(
                    beforeCommand,
                    beforeExecuteEventData);

                var afterExecuteEventData = new
                {
                    OperationId = operationId,
                    Command     = sqlCommand,
                    Timestamp   = 2000000L,
                };

                this.fakeSqlClientDiagnosticSource.Write(
                    afterCommand,
                    afterExecuteEventData);
            }

            Assert.Equal(2, spanProcessor.Invocations.Count); // begin and end was called

            VerifyActivityData(sqlCommand.CommandType, sqlCommand.CommandText, captureStoredProcedureCommandName, captureTextCommandContent, false, sqlConnection.DataSource, (Activity)spanProcessor.Invocations[1].Arguments[0]);
        }
示例#20
0
        public void SetStatus()
        {
            using var openTelemetrySdk = OpenTelemetrySdk.EnableOpenTelemetry(b => b
                                                                              .AddActivitySource(ActivitySourceName));

            using var source   = new ActivitySource(ActivitySourceName);
            using var activity = source.StartActivity(ActivityName);
            activity.SetStatus(Status.Ok);
            activity?.Stop();

            Assert.True(activity.GetStatus().IsOk);
        }
示例#21
0
        public void SetCancelledStatus()
        {
            using var openTelemetrySdk = OpenTelemetrySdk.EnableOpenTelemetry(b => b
                                                                              .AddActivitySource(ActivitySourceName));

            using var source   = new ActivitySource(ActivitySourceName);
            using var activity = source.StartActivity(ActivityName);
            activity.SetStatus(Status.Cancelled);
            activity?.Stop();

            Assert.True(activity.GetStatus().CanonicalCode.Equals(Status.Cancelled.CanonicalCode));
        }
        public void DefaultResourceGetsAssociatedWithActivityIfNoneConfigured()
        {
            using var activitySource = new ActivitySource(nameof(this.ResourceGetsAssociatedWithActivity));
            var expectedResource = Resource.Empty;

            using var openTelemetry = OpenTelemetrySdk.EnableOpenTelemetry(
                      (builder) => builder.AddActivitySource(nameof(this.ResourceGetsAssociatedWithActivity)));

            using (var root = activitySource.StartActivity("root"))
            {
                Assert.Equal(expectedResource, root.GetResource());
            }
        }
示例#23
0
        public async Task HttpDependenciesInstrumentationInjectsHeadersAsync()
        {
            var spanProcessor = new Mock <ActivityProcessor>();
            var request       = new HttpRequestMessage
            {
                RequestUri = new Uri(this.url),
                Method     = new HttpMethod("GET"),
            };

            var parent = new Activity("parent")
                         .SetIdFormat(ActivityIdFormat.W3C)
                         .Start();

            parent.TraceStateString   = "k1=v1,k2=v2";
            parent.ActivityTraceFlags = ActivityTraceFlags.Recorded;

            // Ensure that the header value func does not throw if the header key can't be found
            var mockTextFormat = new Mock <ITextFormatActivity>();
            var isInjectedHeaderValueGetterThrows = false;

            mockTextFormat
            .Setup(x => x.IsInjected(It.IsAny <HttpRequestMessage>(), It.IsAny <Func <HttpRequestMessage, string, IEnumerable <string> > >()))
            .Callback <HttpRequestMessage, Func <HttpRequestMessage, string, IEnumerable <string> > >(
                (carrier, getter) =>
            {
                try
                {
                    // traceparent doesn't exist
                    getter(carrier, "traceparent");
                }
                catch
                {
                    isInjectedHeaderValueGetterThrows = true;
                }
            });

            using (OpenTelemetrySdk.EnableOpenTelemetry(
                       (builder) => builder.AddHttpClientDependencyInstrumentation(o => o.TextFormat = mockTextFormat.Object)
                       .AddProcessorPipeline(p => p.AddProcessor(n => spanProcessor.Object))))
            {
                using var c = new HttpClient();
                await c.SendAsync(request);
            }

            Assert.Equal(2, spanProcessor.Invocations.Count); // begin and end was called
            var span = (Activity)spanProcessor.Invocations[1].Arguments[0];

            Assert.Equal(parent.TraceId, span.Context.TraceId);
            Assert.Equal(parent.SpanId, span.ParentSpanId);
            Assert.NotEqual(parent.SpanId, span.Context.SpanId);
            Assert.NotEqual(default, span.Context.SpanId);
        public void ResourceGetsAssociatedWithActivity()
        {
            using var activitySource = new ActivitySource(nameof(this.ResourceGetsAssociatedWithActivity));
            var expectedResource = OpenTelemetry.Resources.Resources.CreateServiceResource("ServiceNameAbc");

            using var openTelemetry = OpenTelemetrySdk.EnableOpenTelemetry(
                      (builder) => builder.AddActivitySource(nameof(this.ResourceGetsAssociatedWithActivity))
                      .SetResource(expectedResource));

            using (var root = activitySource.StartActivity("root"))
            {
                Assert.Equal(expectedResource, root.GetResource());
            }
        }
示例#25
0
        public OpenTelemetrySdkBenchmarks()
        {
            using var openTelemetryAlwaysOnSample = OpenTelemetrySdk.EnableOpenTelemetry(
                      (builder) => builder.AddActivitySource("AlwaysOnSample").SetSampler(new AlwaysOnSampler()));

            using var openTelemetryAlwaysOffSample = OpenTelemetrySdk.EnableOpenTelemetry(
                      (builder) => builder.AddActivitySource("AlwaysOffSample").SetSampler(new AlwaysOffSampler()));

            using var openTelemetryNoOp = OpenTelemetrySdk.EnableOpenTelemetry(null);

            this.alwaysSampleTracer = TracerProvider.GetTracer("AlwaysOnSample");
            this.neverSampleTracer  = TracerProvider.GetTracer("AlwaysOffSample");
            this.noopTracer         = TracerProvider.GetTracer("NoOp");
        }
示例#26
0
        internal static object Run(string zipkinUri, bool useActivitySource)
        {
            if (useActivitySource)
            {
                // Enable OpenTelemetry for the sources "Samples.SampleServer" and "Samples.SampleClient"
                // and use the Zipkin exporter.
                using var openTelemetry = OpenTelemetrySdk.EnableOpenTelemetry(
                          builder => builder
                          .AddActivitySource("Samples.SampleServer")
                          .AddActivitySource("Samples.SampleClient")
                          .UseZipkinActivityExporter(o =>
                {
                    o.ServiceName = "test-zipkin";
                    o.Endpoint    = new Uri(zipkinUri);
                }));

                using (var sample = new InstrumentationWithActivitySource())
                {
                    sample.Start();

                    Console.WriteLine("Sample is running on the background, press ENTER to stop");
                    Console.ReadLine();
                }
            }
            else
            {
                // Configure exporter to export traces to Zipkin
                using (var tracerFactory = TracerFactory.Create(builder => builder
                                                                .UseZipkin(o =>
                {
                    o.ServiceName = "test-zipkin";
                    o.Endpoint = new Uri(zipkinUri);
                })))
                {
                    var tracer = tracerFactory.GetTracer("zipkin-test");

                    // Create a scoped span. It will end automatically when using statement ends
                    using (tracer.WithSpan(tracer.StartSpan("Main")))
                    {
                        Console.WriteLine("About to do a busy work");
                        for (var i = 0; i < 10; i++)
                        {
                            DoWork(i, tracer);
                        }
                    }
                }
            }

            return(null);
        }
示例#27
0
        public void CancelWithExporterTimeoutMilliSeconds()
        {
            var activityExporter = new TestActivityExporter(null);

            using var activityProcessor = new BatchingActivityProcessor(activityExporter, 128, TimeSpan.FromMilliseconds(0), TimeSpan.FromMilliseconds(0), 1);
            using var openTelemetrySdk  = OpenTelemetrySdk.EnableOpenTelemetry(b => b
                                                                               .AddActivitySource(ActivitySourceName)
                                                                               .SetSampler(new AlwaysOnActivitySampler())
                                                                               .AddProcessorPipeline(pp => pp.AddProcessor(ap => activityProcessor)));

            var activity1 = this.CreateActivity(ActivityName1);

            var exported = this.WaitForActivities(activityExporter, 0, DefaultTimeout);
        }
        public RedisProfilerEntryToActivityConverterTests()
        {
            var connectionOptions = new ConfigurationOptions
            {
                AbortOnConnectFail = false,
            };

            connectionOptions.EndPoints.Add("localhost:6379");

            this.connection = ConnectionMultiplexer.Connect(connectionOptions);

            this.sdk = OpenTelemetrySdk.EnableOpenTelemetry(
                (builder) => builder.AddRedisInstrumentation(this.connection));
        }
示例#29
0
        public void SetStatusWithDescription()
        {
            using var openTelemetrySdk = OpenTelemetrySdk.EnableOpenTelemetry(b => b
                                                                              .AddActivitySource(ActivitySourceName));

            using var source   = new ActivitySource(ActivitySourceName);
            using var activity = source.StartActivity(ActivityName);
            activity.SetStatus(Status.NotFound.WithDescription("Not Found"));
            activity?.Stop();

            var status = activity.GetStatus();

            Assert.Equal(StatusCanonicalCode.NotFound, status.CanonicalCode);
            Assert.Equal("Not Found", status.Description);
        }
        public void ThrowsInExporter()
        {
            this.activityExporter = new TestActivityExporter(_ => throw new ArgumentException("123"));
            this.openTelemetry    = OpenTelemetrySdk.EnableOpenTelemetry(b => b
                                                                         .AddActivitySource("cijo")
                                                                         .AddProcessorPipeline(p => p
                                                                                               .SetExporter(this.activityExporter)
                                                                                               .SetExportingProcessor(e => new SimpleActivityProcessor(e))));

            ActivitySource source   = new ActivitySource("cijo");
            var            activity = source.StartActivity("somename");

            // does not throw
            activity.Stop();
        }