public void GetStatusWithNoStatusInActivity()
        {
            using var openTelemetrySdk = OpenTelemetrySdk.CreateTracerProvider(b => b
                                                                               .AddActivitySource(ActivitySourceName));

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

            Assert.False(activity.GetStatus().IsValid);
        }
 public SimpleActivityProcessorTest()
 {
     this.activityExporter = new TestActivityExporter(null);
     this.openTelemetry    = OpenTelemetrySdk.CreateTracerProvider(b => b
                                                                   .AddActivitySource(ActivitySourceName)
                                                                   .AddProcessorPipeline(p => p
                                                                                         .SetExporter(this.activityExporter)
                                                                                         .SetExportingProcessor(e => new SimpleActivityProcessor(e)))
                                                                   .SetSampler(new AlwaysOnSampler()));
     this.activitySource = new ActivitySource(ActivitySourceName);
 }
        public void SetCancelledStatus()
        {
            using var openTelemetrySdk = OpenTelemetrySdk.CreateTracerProvider(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 SetStatus()
        {
            using var openTelemetrySdk = OpenTelemetrySdk.CreateTracerProvider(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);
        }
        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.CreateTracerProvider(
                       (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]);
        }
예제 #6
0
        public void DefaultResourceGetsAssociatedWithActivityIfNoneConfigured()
        {
            using var activitySource = new ActivitySource(nameof(this.ResourceGetsAssociatedWithActivity));
            var expectedResource = Resource.Empty;

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

            using (var root = activitySource.StartActivity("root"))
            {
                Assert.Equal(expectedResource, root.GetResource());
            }
        }
예제 #7
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.CreateTracerProvider(
                       (builder) => builder.AddHttpClientInstrumentation(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 OpenTelemetrySdkBenchmarks()
        {
            using var openTelemetryAlwaysOnSample = OpenTelemetrySdk.CreateTracerProvider(
                      (builder) => builder.AddActivitySource("AlwaysOnSample").SetSampler(new AlwaysOnSampler()));

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

            using var openTelemetryNoOp = OpenTelemetrySdk.CreateTracerProvider(null);

            this.alwaysSampleTracer = TracerProvider.Default.GetTracer("AlwaysOnSample");
            this.neverSampleTracer  = TracerProvider.Default.GetTracer("AlwaysOffSample");
            this.noopTracer         = TracerProvider.Default.GetTracer("NoOp");
        }
        public RedisProfilerEntryToActivityConverterTests()
        {
            var connectionOptions = new ConfigurationOptions
            {
                AbortOnConnectFail = false,
            };

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

            this.connection = ConnectionMultiplexer.Connect(connectionOptions);

            this.sdk = OpenTelemetrySdk.CreateTracerProvider(
                (builder) => builder.AddRedisInstrumentation(this.connection));
        }
예제 #10
0
        public void ResourceGetsAssociatedWithActivity()
        {
            using var activitySource = new ActivitySource(nameof(this.ResourceGetsAssociatedWithActivity));
            var expectedResource = Resources.Resources.CreateServiceResource("ServiceNameAbc");

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

            using (var root = activitySource.StartActivity("root"))
            {
                Assert.Equal(expectedResource, root.GetResource());
            }
        }
        public void ThrowsInExporter()
        {
            this.activityExporter = new TestActivityExporter(_ => throw new ArgumentException("123"));
            this.openTelemetry    = OpenTelemetrySdk.CreateTracerProvider(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();
        }
        public void SetStatusWithDescription()
        {
            using var openTelemetrySdk = OpenTelemetrySdk.CreateTracerProvider(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);
        }
        internal static object Run(string zipkinUri)
        {
            /*
             * Setup redis service inside local docker.
             * docker run --name opentelemetry-redis-test -d -p 6379:6379 redis
             *
             * If you face any issue with the first command, do the following ones:
             * docker exec -it opentelemetry-redis-test sh
             * redis-cli
             * set bind 0.0.0.0
             * save
             */

            // connect to the redis server. The default port 6379 will be used.
            var connection = ConnectionMultiplexer.Connect("localhost");

            // Configure exporter to export traces to Zipkin
            using var openTelemetry = OpenTelemetrySdk.CreateTracerProvider(
                      builder => builder
                      .UseZipkinExporter(o =>
            {
                o.ServiceName = "redis-test";
                o.Endpoint    = new Uri(zipkinUri);
            })
                      .AddRedisInstrumentation(connection, options =>
            {
                // changing flushinterval from 10s to 5s
                options.FlushInterval = TimeSpan.FromSeconds(5);
            })
                      .AddActivitySource("redis-test"));

            ActivitySource activitySource = new ActivitySource("redis-test");

            // select a database (by default, DB = 0)
            var db = connection.GetDatabase();

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

            return(null);
        }
예제 #14
0
        public void EventSourceFakeUnknownEventWithNullPayloadTest()
        {
            using FakeMisbehavingSqlEventSource fakeSqlEventSource = new FakeMisbehavingSqlEventSource();

            var activityProcessor = new Mock <ActivityProcessor>();

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

            fakeSqlEventSource.WriteUnknownEventWithNullPayload();

            Assert.Equal(0, activityProcessor.Invocations.Count);
        }
        protected void Application_Start()
        {
            this.openTelemetry = OpenTelemetrySdk.CreateTracerProvider(
                (builder) => builder.AddDependencyInstrumentation()
                .AddRequestInstrumentation()
                .UseJaegerExporter(c =>
            {
                c.AgentHost = "localhost";
                c.AgentPort = 6831;
            }));

            GlobalConfiguration.Configure(WebApiConfig.Register);

            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
예제 #16
0
        public void CancelWithExporterTimeoutMilliseconds()
        {
            using var inMemoryEventListener = new InMemoryEventListener();
            var activityExporter = new TestActivityExporter(null, sleepMilliseconds: 5000);

            using var activityProcessor = new BatchingActivityProcessor(activityExporter, 128, TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(0), 1);
            using (var openTelemetrySdk = OpenTelemetrySdk.CreateTracerProvider(b => b
                                                                                .AddActivitySource(ActivitySourceName)
                                                                                .SetSampler(new AlwaysOnSampler())
                                                                                .AddProcessorPipeline(pp => pp.AddProcessor(ap => activityProcessor))))
            {
                var activity1 = this.CreateActivity(ActivityName1);
            } // Force everything to flush out of the processor.

            Assert.Contains(inMemoryEventListener.Events, (e) => e.EventId == 23);
        }
        public void SuccessfulCommandTest(
            CommandType commandType,
            string commandText,
            bool captureStoredProcedureCommandName,
            bool captureTextCommandContent = false,
            bool isFailure = false)
        {
            var activityProcessor = new Mock <ActivityProcessor>();

            using var shutdownSignal = OpenTelemetrySdk.CreateTracerProvider(b =>
            {
                b.AddProcessorPipeline(c => c.AddProcessor(ap => activityProcessor.Object));
                b.AddSqlClientDependencyInstrumentation(options =>
                {
                    options.SetStoredProcedureCommandName = captureStoredProcedureCommandName;
                    options.SetTextCommandContent         = captureTextCommandContent;
                });
            });

            using SqlConnection sqlConnection = new SqlConnection(SqlConnectionString);

            sqlConnection.Open();

            string dataSource = sqlConnection.DataSource;

            sqlConnection.ChangeDatabase("master");

            using SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection)
                  {
                      CommandType = commandType,
                  };

            try
            {
                sqlCommand.ExecuteNonQuery();
            }
            catch
            {
            }

            Assert.Equal(2, activityProcessor.Invocations.Count);

            var activity = (Activity)activityProcessor.Invocations[1].Arguments[0];

            VerifyActivityData(commandType, commandText, captureStoredProcedureCommandName, captureTextCommandContent, isFailure, dataSource, activity);
        }
예제 #18
0
        public void EventSourceFakeTests(
            CommandType commandType,
            string commandText,
            bool captureText,
            bool isFailure         = false,
            int sqlExceptionNumber = 0,
            bool enableConnectionLevelAttributes = false)
        {
            using FakeBehavingSqlEventSource fakeSqlEventSource = new FakeBehavingSqlEventSource();

            var activityProcessor = new Mock <ActivityProcessor>();

            using var shutdownSignal = OpenTelemetrySdk.CreateTracerProvider(b =>
            {
                b.AddProcessorPipeline(c => c.AddProcessor(ap => activityProcessor.Object));
                b.AddSqlClientDependencyInstrumentation(options =>
                {
                    options.SetStoredProcedureCommandName   = captureText;
                    options.EnableConnectionLevelAttributes = enableConnectionLevelAttributes;
                });
            });

            int objectId = Guid.NewGuid().GetHashCode();

            fakeSqlEventSource.WriteBeginExecuteEvent(objectId, "127.0.0.1", "master", commandType == CommandType.StoredProcedure ? commandText : string.Empty);

            // success is stored in the first bit in compositeState 0b001
            int successFlag = !isFailure ? 1 : 0;

            // isSqlException is stored in the second bit in compositeState 0b010
            int isSqlExceptionFlag = sqlExceptionNumber > 0 ? 2 : 0;

            // synchronous state is stored in the third bit in compositeState 0b100
            int synchronousFlag = false ? 4 : 0;

            int compositeState = successFlag | isSqlExceptionFlag | synchronousFlag;

            fakeSqlEventSource.WriteEndExecuteEvent(objectId, compositeState, sqlExceptionNumber);

            Assert.Equal(2, activityProcessor.Invocations.Count);

            var activity = (Activity)activityProcessor.Invocations[1].Arguments[0];

            VerifyActivityData(commandType, commandText, captureText, isFailure, "127.0.0.1", activity, enableConnectionLevelAttributes);
        }
        public async Task CustomTextFormat()
        {
            var spanProcessor = new Mock <ActivityProcessor>();

            var expectedTraceId = ActivityTraceId.CreateRandom();
            var expectedSpanId  = ActivitySpanId.CreateRandom();

            var textFormat = new Mock <ITextFormatActivity>();

            textFormat.Setup(m => m.Extract <HttpRequest>(It.IsAny <HttpRequest>(), It.IsAny <Func <HttpRequest, string, IEnumerable <string> > >())).Returns(new ActivityContext(
                                                                                                                                                                  expectedTraceId,
                                                                                                                                                                  expectedSpanId,
                                                                                                                                                                  ActivityTraceFlags.Recorded));

            // Arrange
            using (var testFactory = this.factory
                                     .WithWebHostBuilder(builder =>
                                                         builder.ConfigureTestServices(services =>
            {
                this.openTelemetrySdk = OpenTelemetrySdk.CreateTracerProvider(
                    (builder) => builder.AddRequestInstrumentation((opt) => opt.TextFormat = textFormat.Object)
                    .AddProcessorPipeline(p => p.AddProcessor(n => spanProcessor.Object)));
            })))
            {
                using var client = testFactory.CreateClient();
                var response = await client.GetAsync("/api/values/2");

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

                WaitForProcessorInvocations(spanProcessor, 2);
            }

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

            Assert.Equal(ActivityKind.Server, span.Kind);
            Assert.True(span.Duration != TimeSpan.Zero);
            Assert.Equal("api/Values/{id}", span.DisplayName);
            Assert.Equal("/api/values/2", span.Tags.FirstOrDefault(i => i.Key == SpanAttributeConstants.HttpPathKey).Value);

            Assert.Equal(expectedTraceId, span.Context.TraceId);
            Assert.Equal(expectedSpanId, span.ParentSpanId);
        }
예제 #20
0
        public async Task ShutdownOnNotEmptyQueueNotFullFlush()
        {
            const int batchSize         = 25;
            int       exportCalledCount = 0;

            var activityExporter = new TestActivityExporter(_ => Interlocked.Increment(ref exportCalledCount), 30000);

            using var activityProcessor =
                      new BatchingActivityProcessor(activityExporter, 128, DefaultDelay, DefaultTimeout, batchSize);
            using (var openTelemetrySdk = OpenTelemetrySdk.CreateTracerProvider(b => b
                                                                                .AddActivitySource(ActivitySourceName)
                                                                                .SetSampler(new AlwaysOnSampler())
                                                                                .AddProcessorPipeline(pp => pp.AddProcessor(ap => activityProcessor))))
            {
                var activities = new List <Activity>();
                for (int i = 0; i < 100; i++)
                {
                    activities.Add(this.CreateActivity(i.ToString()));
                }

                Assert.True(activityExporter.ExportedActivities.Length < activities.Count);

                // we won't be able to export all before cancellation will fire
                using (var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)))
                {
                    bool canceled;
                    try
                    {
                        await activityProcessor.ShutdownAsync(cts.Token);

                        canceled = false;
                    }
                    catch (OperationCanceledException)
                    {
                        canceled = true;
                    }

                    Assert.True(canceled);
                }

                var exportedCount = activityExporter.ExportedActivities.Length;
                Assert.True(exportedCount < activities.Count);
            }
        }
        public void SqlClientErrorsAreCollectedSuccessfully(string beforeCommand, string errorCommand)
        {
            using var sqlConnection = new SqlConnection(TestConnectionString);
            using var sqlCommand    = sqlConnection.CreateCommand();

            var spanProcessor = new Mock <ActivityProcessor>();

            using (OpenTelemetrySdk.CreateTracerProvider(
                       (builder) => builder.AddSqlClientDependencyInstrumentation()
                       .AddProcessorPipeline(p => p.AddProcessor(n => spanProcessor.Object))))
            {
                var operationId = Guid.NewGuid();
                sqlCommand.CommandText = "SP_GetOrders";
                sqlCommand.CommandType = CommandType.StoredProcedure;

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

                this.fakeSqlClientDiagnosticSource.Write(
                    beforeCommand,
                    beforeExecuteEventData);

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

                this.fakeSqlClientDiagnosticSource.Write(
                    errorCommand,
                    commandErrorEventData);
            }

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

            VerifyActivityData(sqlCommand.CommandType, sqlCommand.CommandText, true, false, true, sqlConnection.DataSource, (Activity)spanProcessor.Invocations[1].Arguments[0]);
        }
예제 #22
0
        public void ExportDifferentSampledActivities()
        {
            var activityExporter = new TestActivityExporter(null);

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

            var activity1 = this.CreateActivity(ActivityName1);
            var activity2 = this.CreateActivity(ActivityName2);

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

            Assert.Equal(2, exported.Length);
            Assert.Contains(activity1, exported);
            Assert.Contains(activity2, exported);
        }
예제 #23
0
        public async Task ShutdownOnNotEmptyQueueFullFlush()
        {
            const int batchSize         = 75;
            int       exportCalledCount = 0;
            var       activityExporter  = new TestActivityExporter(_ => Interlocked.Increment(ref exportCalledCount));

            using var activityProcessor =
                      new BatchingActivityProcessor(activityExporter, 128, DefaultDelay, DefaultTimeout, batchSize);
            using (var openTelemetrySdk = OpenTelemetrySdk.CreateTracerProvider(b => b
                                                                                .AddActivitySource(ActivitySourceName)
                                                                                .SetSampler(new AlwaysOnSampler())
                                                                                .AddProcessorPipeline(pp => pp.AddProcessor(ap => activityProcessor))))
            {
                using var inMemoryEventListener = new InMemoryEventListener();
                var activities = new List <Activity>();
                for (int i = 0; i < 100; i++)
                {
                    activities.Add(this.CreateActivity(i.ToString()));
                }

                Assert.True(activityExporter.ExportedActivities.Length < activities.Count);
                using (var cts = new CancellationTokenSource(DefaultTimeout))
                {
                    await activityProcessor.ShutdownAsync(cts.Token);
                }

                // Get the shutdown event.
                // 2 is the EventId for OpenTelemetrySdkEventSource.ShutdownEvent
                // TODO: Expose event ids as internal, so tests can access them more reliably.
                var shutdownEvent = inMemoryEventListener.Events.Where((e) => e.EventId == 2).First();

                int droppedCount = 0;
                if (shutdownEvent != null)
                {
                    // There is a single payload which is the number of items left in buffer at shutdown.
                    droppedCount = (int)shutdownEvent.Payload[0];
                }

                Assert.True(activityExporter.WasShutDown);
                Assert.Equal(activities.Count, droppedCount + activityExporter.ExportedActivities.Length);
                Assert.InRange(exportCalledCount, activities.Count / batchSize, activities.Count);
            }
        }
예제 #24
0
        internal static object Run()
        {
            var zpagesOptions = new ZPagesExporterOptions()
            {
                Url = "http://localhost:7284/rpcz/", RetentionTime = 3600000
            };
            var zpagesExporter  = new ZPagesExporter(zpagesOptions);
            var zpagesProcessor = new ZPagesProcessor(zpagesExporter);
            var httpServer      = new ZPagesExporterStatsHttpServer(zpagesExporter);

            // Start the server
            httpServer.Start();

            using var openTelemetry = OpenTelemetrySdk.CreateTracerProvider(
                      builder => builder
                      .AddActivitySource("zpages-test")
                      .UseZPagesExporter(
                          processorConfigure: processor => processor
                          .AddProcessor((next) => zpagesProcessor)));

            ActivitySource activitySource = new ActivitySource("zpages-test");

            while (true)
            {
                // Create a scoped activity. It will end automatically when using statement ends
                using (activitySource.StartActivity("Main"))
                {
                    System.Console.WriteLine("About to do a busy work in Main");
                }

                Thread.Sleep(3000);

                // Create a scoped activity. It will end automatically when using statement ends
                using (activitySource.StartActivity("Test"))
                {
                    System.Console.WriteLine("About to do a busy work in Test");
                }

                Thread.Sleep(5000);
            }
        }
        internal static object Run(ConsoleOptions options)
        {
            // Enable TracerProvider for the source "MyCompany.MyProduct.MyWebServer"
            // and use a single pipeline with a custom MyProcessor, and Console exporter.
            using var tracerProvider = OpenTelemetrySdk.CreateTracerProvider(
                      (builder) => builder.AddActivitySource("MyCompany.MyProduct.MyWebServer")
                      .SetResource(Resources.CreateServiceResource("MyServiceName"))
                      .SetSampler(Sampler)
                      .UseConsoleExporter(opt => opt.DisplayAsJson = options.DisplayAsJson,
                                          (p) => p.AddProcessor((next) => new MyProcessor(next))));

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

            Thread[] threads = new Thread[6];

            long result = 0;

            for (int i = 0; i < threads.Length; i++)
            {
                threads[i] = new Thread(() =>
                {
                    result = SampleThreadTest(5);
                });
            }

            foreach (Thread thread in threads)
            {
                thread.Start();

                System.Console.WriteLine("thread {0} has result {1}", thread.ManagedThreadId, result);
            }

            foreach (Thread thread in threads)
            {
                thread.Join();
            }

            // System.Console.WriteLine("result from threads is: {0}", result);
            return(null);
        }
예제 #26
0
        internal static object Run()
        {
            System.Console.WriteLine("Hello World!");

            using var openTelemetry = OpenTelemetrySdk.CreateTracerProvider(
                      (builder) => builder.AddHttpClientInstrumentation()
                      .SetResource(Resources.CreateServiceResource("http-service-example"))
                      .AddActivitySource("http-client-test")
                      .UseConsoleExporter(opt => opt.DisplayAsJson = false));

            var source = new ActivitySource("http-client-test");

            using (var parent = source.StartActivity("incoming request", ActivityKind.Server))
            {
                using var client = new HttpClient();
                client.GetStringAsync("http://bing.com").GetAwaiter().GetResult();
            }

            System.Console.ReadLine();

            return(null);
        }
        public async Task SuccessfulTemplateControllerCallUsesParentContext()
        {
            var spanProcessor = new Mock <ActivityProcessor>();

            var expectedTraceId = ActivityTraceId.CreateRandom();
            var expectedSpanId  = ActivitySpanId.CreateRandom();

            // Arrange
            using (var testFactory = this.factory
                                     .WithWebHostBuilder(builder =>
                                                         builder.ConfigureTestServices(services =>
            {
                this.openTelemetrySdk = OpenTelemetrySdk.CreateTracerProvider((builder) => builder.AddRequestInstrumentation()
                                                                              .AddProcessorPipeline(p => p.AddProcessor(n => spanProcessor.Object)));
            })))
            {
                using var client = testFactory.CreateClient();
                var request = new HttpRequestMessage(HttpMethod.Get, "/api/values/2");
                request.Headers.Add("traceparent", $"00-{expectedTraceId}-{expectedSpanId}-01");

                // Act
                var response = await client.SendAsync(request);

                // 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/{id}", span.DisplayName);
            Assert.Equal("/api/values/2", span.Tags.FirstOrDefault(i => i.Key == SpanAttributeConstants.HttpPathKey).Value);

            Assert.Equal(expectedTraceId, span.Context.TraceId);
            Assert.Equal(expectedSpanId, span.ParentSpanId);
        }
예제 #28
0
        public void SuccessfulCommandTest(string value)
        {
            var connectionOptions = new ConfigurationOptions
            {
                AbortOnConnectFail = true,
            };

            connectionOptions.EndPoints.Add(RedisEndPoint);

            using var connection = ConnectionMultiplexer.Connect(connectionOptions);

            var activityProcessor = new Mock <ActivityProcessor>();

            using (OpenTelemetrySdk.CreateTracerProvider(b =>
            {
                b.AddProcessorPipeline(c => c.AddProcessor(ap => activityProcessor.Object));
                b.AddRedisInstrumentation(connection);
            }))
            {
                var db = connection.GetDatabase();

                bool set = db.StringSet("key1", value, TimeSpan.FromSeconds(60));

                Assert.True(set);

                var redisValue = db.StringGet("key1");

                Assert.True(redisValue.HasValue);
                Assert.Equal(value, redisValue.ToString());
            }

            // Disposing SDK should flush the Redis profiling session immediately.

            Assert.Equal(4, activityProcessor.Invocations.Count);

            VerifyActivityData((Activity)activityProcessor.Invocations[1].Arguments[0], true, connection.GetEndPoints()[0]);
            VerifyActivityData((Activity)activityProcessor.Invocations[3].Arguments[0], false, connection.GetEndPoints()[0]);
        }
예제 #29
0
        public void ExportMoreActivitiesThanTheMaxBatchSize()
        {
            var exporterCalled    = new ManualResetEvent(false);
            int exportCalledCount = 0;
            var activityExporter  = new TestActivityExporter(_ =>
            {
                exporterCalled.Set();
                Interlocked.Increment(ref exportCalledCount);
            });

            using var activityProcessor = new BatchingActivityProcessor(activityExporter, 128, DefaultDelay, DefaultTimeout, 3);
            using var openTelemetrySdk  = OpenTelemetrySdk.CreateTracerProvider(b => b
                                                                                .AddActivitySource(ActivitySourceName)
                                                                                .SetSampler(new AlwaysOnSampler())
                                                                                .AddProcessorPipeline(pp => pp.AddProcessor(ap => activityProcessor)));

            var activity1 = this.CreateActivity(ActivityName1);
            var activity2 = this.CreateActivity(ActivityName1);
            var activity3 = this.CreateActivity(ActivityName1);
            var activity4 = this.CreateActivity(ActivityName1);
            var activity5 = this.CreateActivity(ActivityName1);
            var activity6 = this.CreateActivity(ActivityName1);

            // wait for exporter to be called to stabilize tests on the build server
            exporterCalled.WaitOne(TimeSpan.FromSeconds(10));

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

            Assert.InRange(exportCalledCount, 2, 6);

            Assert.Equal(6, exported.Count());
            Assert.Contains(activity1, exported);
            Assert.Contains(activity2, exported);
            Assert.Contains(activity3, exported);
            Assert.Contains(activity4, exported);
            Assert.Contains(activity5, exported);
            Assert.Contains(activity6, exported);
        }
        public async Task FilterOutRequest()
        {
            var spanProcessor = new Mock <ActivityProcessor>();

            void ConfigureTestServices(IServiceCollection services)
            {
                this.openTelemetrySdk = OpenTelemetrySdk.CreateTracerProvider(
                    (builder) =>
                    builder.AddRequestInstrumentation((opt) => opt.RequestFilter = (ctx) => ctx.Request.Path != "/api/values/2")
                    .AddProcessorPipeline(p => p.AddProcessor(n => spanProcessor.Object)));
            }

            // Arrange
            using (var testFactory = this.factory
                                     .WithWebHostBuilder(builder =>
                                                         builder.ConfigureTestServices(ConfigureTestServices)))
            {
                using var client = testFactory.CreateClient();

                // Act
                var response1 = await client.GetAsync("/api/values");

                var response2 = await client.GetAsync("/api/values/2");

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

                WaitForProcessorInvocations(spanProcessor, 2);
            }

            // we should only create one span and never call processor with another
            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);
        }