Exemple #1
0
        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 tracerProvider = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                       .AddSource("MyCompany.MyProduct.MyWebServer")
                                       .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("MyServiceName"))
                                       .AddConsoleExporter()
                                       .Build();

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

            var tracer = TracerProvider.Default.GetTracer("MyCompany.MyProduct.MyWebServer");

            using (var parentSpan = tracer.StartActiveSpan("parent span"))
            {
                parentSpan.SetAttribute("mystring", "value");
                parentSpan.SetAttribute("myint", 100);
                parentSpan.SetAttribute("mydouble", 101.089);
                parentSpan.SetAttribute("mybool", true);
                parentSpan.UpdateName("parent span new name");

                var childSpan = tracer.StartSpan("child span");
                childSpan.AddEvent("sample event").SetAttribute("ch", "value").SetAttribute("more", "attributes");
                childSpan.SetStatus(Status.Ok);
                childSpan.End();
            }

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

            return(null);
        }
        public async Task HttpWebRequestInstrumentationInjectsHeadersAsync()
        {
            var activityProcessor = new Mock <BaseProcessor <Activity> >();

            using var shutdownSignal = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                       .AddProcessor(activityProcessor.Object)
                                       .AddHttpClientInstrumentation()
                                       .Build();

            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(3, activityProcessor.Invocations.Count);  // SetParentProvider/Begin/End called
            var activity = (Activity)activityProcessor.Invocations[2].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);
        private static object RunWithActivitySource()
        {
            // Enable OpenTelemetry for the sources "Samples.SampleServer" and "Samples.SampleClient"
            // and use Console exporter.
            using var openTelemetry = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                      .AddSource("Samples.SampleClient", "Samples.SampleServer")
                                      .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("console-test"))
                                      .AddProcessor(new MyProcessor()) // This must be added before ConsoleExporter
                                      .AddConsoleExporter()
                                      .Build();

            // The above line is required only in applications
            // which decide to use OpenTelemetry.
            using (var sample = new InstrumentationWithActivitySource())
            {
                sample.Start();

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

            return(null);
        }
        public void SetErrorStatusOnExceptionDisabled()
        {
            using var activitySource = new ActivitySource(ActivitySourceName);
            using var tracerProvider = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                       .AddSource(ActivitySourceName)
                                       .SetSampler(new AlwaysOnSampler())
                                       .SetErrorStatusOnException()
                                       .SetErrorStatusOnException(false)
                                       .Build();

            Activity activity = null;

            try
            {
                using (activity = activitySource.StartActivity("Activity"))
                {
                    throw new Exception("Oops!");
                }
            }
            catch (Exception)
            {
            }

            Assert.Equal(StatusCode.Unset, activity.GetStatus().StatusCode);
        }
        public void TracerSdkSetsActivityDataRequestedToFalseWhenSuppressInstrumentationIsTrueForLegacyActivity()
        {
            using TestActivityProcessor testActivityProcessor = new TestActivityProcessor();

            bool startCalled = false;
            bool endCalled   = false;

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

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

            using var openTelemetry = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                      .AddLegacySource("random")
                                      .AddProcessor(testActivityProcessor)
                                      .SetSampler(new AlwaysOnSampler())
                                      .Build();

            using (SuppressInstrumentationScope.Begin(true))
            {
                using var activity = new Activity("random").Start();
                Assert.False(activity.IsAllDataRequested);
            }

            Assert.False(startCalled);
            Assert.False(endCalled);
        }
        public void EnumerateLinksNonempty()
        {
            using var openTelemetrySdk = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                         .AddSource(ActivitySourceName)
                                         .Build();

            var links = new[]
 public void GetCurrentSpanBlank()
 {
     using var openTelemetry = OpenTelemetrySdk.CreateTracerProviderBuilder()
                               .AddSource("tracername")
                               .Build();
     Assert.False(Tracer.CurrentSpan.Context.IsValid);
 }
        public void Tracer_StartActiveSpan_CreatesActiveSpan()
        {
            using var openTelemetry = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                      .AddSource("tracername")
                                      .Build();

            var span1 = this.tracer.StartActiveSpan("Test");

            Assert.Equal(span1.Activity.SpanId, Tracer.CurrentSpan.Context.SpanId);

            var span2 = this.tracer.StartActiveSpan("Test", SpanKind.Client);

            Assert.Equal(span2.Activity.SpanId, Tracer.CurrentSpan.Context.SpanId);

            var span = this.tracer.StartSpan("foo");

            Tracer.WithSpan(span);

            var span3 = this.tracer.StartActiveSpan("Test", SpanKind.Client, span);

            Assert.Equal(span3.Activity.SpanId, Tracer.CurrentSpan.Context.SpanId);

            var spanContext = new SpanContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.Recorded);
            var span4       = this.tracer.StartActiveSpan("Test", SpanKind.Client, spanContext);

            Assert.Equal(span4.Activity.SpanId, Tracer.CurrentSpan.Context.SpanId);
        }
        public void ExportResultIsSuccess()
        {
#if NETCOREAPP3_1
            // Adding the OtlpExporter creates a GrpcChannel.
            // This switch must be set before creating a GrpcChannel/HttpClient when calling an insecure gRPC service.
            // See: https://docs.microsoft.com/aspnet/core/grpc/troubleshoot#call-insecure-grpc-services-with-net-core-client
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
#endif

            var exporterOptions = new OtlpExporterOptions
            {
                Endpoint = new System.Uri($"http://{CollectorEndpoint}"),
            };

            var otlpExporter            = new OtlpTraceExporter(exporterOptions);
            var delegatingExporter      = new DelegatingTestExporter <Activity>(otlpExporter);
            var exportActivityProcessor = new SimpleActivityExportProcessor(delegatingExporter);

            var activitySourceName = "otlp.collector.test";

            var builder = OpenTelemetrySdk.CreateTracerProviderBuilder()
                          .AddSource(activitySourceName)
                          .AddProcessor(exportActivityProcessor);

            using var tracerProvider = builder.Build();

            var source   = new ActivitySource(activitySourceName);
            var activity = source.StartActivity("Test Activity");
            activity?.Stop();

            Assert.Single(delegatingExporter.ExportResults);
            Assert.Equal(ExportResult.Success, delegatingExporter.ExportResults[0]);
        }
Exemple #10
0
        public TraceShimBenchmarks()
        {
            Activity.DefaultIdFormat = ActivityIdFormat.W3C;

            OpenTelemetrySdk.CreateTracerProviderBuilder()
            .SetSampler(new AlwaysOnSampler())
            .AddSource("Benchmark.OneProcessor")
            .AddProcessor(new DummyActivityProcessor())
            .Build();

            OpenTelemetrySdk.CreateTracerProviderBuilder()
            .SetSampler(new AlwaysOnSampler())
            .AddSource("Benchmark.TwoProcessors")
            .AddProcessor(new DummyActivityProcessor())
            .AddProcessor(new DummyActivityProcessor())
            .Build();

            OpenTelemetrySdk.CreateTracerProviderBuilder()
            .SetSampler(new AlwaysOnSampler())
            .AddSource("Benchmark.ThreeProcessors")
            .AddProcessor(new DummyActivityProcessor())
            .AddProcessor(new DummyActivityProcessor())
            .AddProcessor(new DummyActivityProcessor())
            .Build();
        }
Exemple #11
0
        internal static object Run(string zipkinUri)
        {
            // Prerequisite for running this example.
            // Setup zipkin inside local docker using following command:
            // docker run -d -p 9411:9411 openzipkin/zipkin

            // To run this example, run the following command from
            // the reporoot\examples\Console\.
            // (eg: C:\repos\opentelemetry-dotnet\examples\Console\)
            //
            // dotnet run zipkin -u http://localhost:9411/api/v2/spans

            // Enable OpenTelemetry for the sources "Samples.SampleServer" and "Samples.SampleClient"
            // and use the Zipkin exporter.
            using var openTelemetry = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                      .AddSource("Samples.SampleClient", "Samples.SampleServer")
                                      .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("zipkin-test"))
                                      .AddZipkinExporter(o =>
            {
                o.Endpoint = new Uri(zipkinUri);
            })
                                      .Build();

            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);
        }
        public void TracerProviderSdkSamplerAttributesAreAppliedToActivity(SamplingDecision sampling)
        {
            var testSampler = new TestSampler();

            testSampler.SamplingAction = (samplingParams) =>
            {
                var attributes = new Dictionary <string, object>();
                attributes.Add("tagkeybysampler", "tagvalueaddedbysampler");
                return(new SamplingResult(sampling, attributes));
            };

            using var activitySource = new ActivitySource(ActivitySourceName);
            using var sdk            = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                       .AddSource(ActivitySourceName)
                                       .SetSampler(testSampler)
                                       .Build();

            using (var rootActivity = activitySource.StartActivity("root"))
            {
                Assert.NotNull(rootActivity);
                Assert.Equal(rootActivity.TraceId, testSampler.LatestSamplingParameters.TraceId);
                if (sampling != SamplingDecision.Drop)
                {
                    Assert.Contains(new KeyValuePair <string, object>("tagkeybysampler", "tagvalueaddedbysampler"), rootActivity.TagObjects);
                }
            }
        }
        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(OpenTelemetrySdk.SuppressInstrumentation);
                Assert.True(a.IsAllDataRequested);     // If Proccessor.OnStart is called, activity's IsAllDataRequested is set to true
                startCalled = true;
            };

            testActivityProcessor.EndAction =
                (a) =>
            {
                Assert.False(OpenTelemetrySdk.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 = OpenTelemetrySdk.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
        }
        private static object RunWithActivitySource(string endpoint)
        {
            // Adding the OtlpExporter creates a GrpcChannel.
            // This switch must be set before creating a GrpcChannel/HttpClient when calling an insecure gRPC service.
            // See: https://docs.microsoft.com/aspnet/core/grpc/troubleshoot#call-insecure-grpc-services-with-net-core-client
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            // Enable OpenTelemetry for the sources "Samples.SampleServer" and "Samples.SampleClient"
            // and use OTLP exporter.
            using var openTelemetry = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                      .AddSource("Samples.SampleClient", "Samples.SampleServer")
                                      .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("otlp-test"))
                                      .AddOtlpExporter(opt => opt.Endpoint = new Uri(endpoint))
                                      .Build();

            // The above line is required only in Applications
            // which decide to use OpenTelemetry.
            using (var sample = new InstrumentationWithActivitySource())
            {
                sample.Start();

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

            return(null);
        }
        public async Task RequestNotCollectedWhenFilterThrowException()
        {
            var activityProcessor = new Mock <BaseProcessor <Activity> >();

            void ConfigureTestServices(IServiceCollection services)
            {
                this.openTelemetrySdk = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                        .AddAspNetCoreInstrumentation((opt) => opt.Filter = (ctx) =>
                {
                    if (ctx.Request.Path == "/api/values/2")
                    {
                        throw new Exception("from InstrumentationFilter");
                    }
                    else
                    {
                        return(true);
                    }
                })
                                        .AddProcessor(activityProcessor.Object)
                                        .Build();
            }

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

                // Act
                using (var inMemoryEventListener = new InMemoryEventListener(AspNetCoreInstrumentationEventSource.Log))
                {
                    var response1 = await client.GetAsync("/api/values");

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

                    response1.EnsureSuccessStatusCode(); // Status Code 200-299
                    response2.EnsureSuccessStatusCode(); // Status Code 200-299
                    Assert.Single(inMemoryEventListener.Events.Where((e) => e.EventId == 3));
                }

                WaitForProcessorInvocations(activityProcessor, 3);
            }

            // As InstrumentationFilter threw, we continue as if the
            // InstrumentationFilter did not exist.

            // List of invocations on the processor
            // 1. SetParentProvider for TracerProviderSdk
            // 2. OnStart for the activity created by AspNetCore for "/api/values" with the OperationName: Microsoft.AspNetCore.Hosting.HttpRequestIn
            // 3. OnEnd for the activity created by AspNetCore for "/api/values" with the OperationName: Microsoft.AspNetCore.Hosting.HttpRequestIn
            // 4. OnStart for the activity created by AspNetCore for "/api/values/2" with the OperationName: Microsoft.AspNetCore.Hosting.HttpRequestIn

            // we should only call Processor.OnEnd for the "/api/values" request
            Assert.Single(activityProcessor.Invocations, invo => invo.Method.Name == "OnEnd");
            var activity = activityProcessor.Invocations.FirstOrDefault(invo => invo.Method.Name == "OnEnd").Arguments[0] as Activity;

            ValidateAspNetCoreActivity(activity, "/api/values");
        }
        public void SqlClientErrorsAreCollectedSuccessfully(string beforeCommand, string errorCommand, bool shouldEnrich = true, bool recordException = false)
        {
            using var sqlConnection = new SqlConnection(TestConnectionString);
            using var sqlCommand    = sqlConnection.CreateCommand();

            var processor = new Mock <BaseProcessor <Activity> >();

            using (OpenTelemetrySdk.CreateTracerProviderBuilder()
                   .AddSqlClientInstrumentation(options =>
            {
                options.RecordException = recordException;
                if (shouldEnrich)
                {
                    options.Enrich = ActivityEnrichment;
                }
            })
                   .AddProcessor(processor.Object)
                   .Build())
            {
                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(5, processor.Invocations.Count); // SetParentProvider/OnStart/OnEnd/OnShutdown/Dispose called.

            VerifyActivityData(
                sqlCommand.CommandType,
                sqlCommand.CommandText,
                true,
                false,
                true,
                recordException,
                sqlConnection.DataSource,
                (Activity)processor.Invocations[2].Arguments[0]);
        }
        public async Task ExtractContextIrrespectiveOfSamplingDecision(SamplingDecision samplingDecision)
        {
            try
            {
                var expectedTraceId      = ActivityTraceId.CreateRandom();
                var expectedParentSpanId = ActivitySpanId.CreateRandom();
                var expectedTraceState   = "rojo=1,congo=2";
                var activityContext      = new ActivityContext(expectedTraceId, expectedParentSpanId, ActivityTraceFlags.Recorded, expectedTraceState);
                var expectedBaggage      = Baggage.SetBaggage("key1", "value1").SetBaggage("key2", "value2");
                OpenTelemetrySdk.SetDefaultTextMapPropagator(new ExtractOnlyPropagator(activityContext, expectedBaggage));

                // Arrange
                using (var testFactory = this.factory
                                         .WithWebHostBuilder(builder =>
                                                             builder.ConfigureTestServices(services =>
                {
                    this.openTelemetrySdk = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                            .SetSampler(new TestSampler(samplingDecision))
                                            .AddAspNetCoreInstrumentation()
                                            .Build();
                })))
                {
                    using var client = testFactory.CreateClient();

                    // Test TraceContext Propagation
                    var request  = new HttpRequestMessage(HttpMethod.Get, "/api/GetChildActivityTraceContext");
                    var response = await client.SendAsync(request);

                    var childActivityTraceContext = JsonConvert.DeserializeObject <Dictionary <string, string> >(response.Content.ReadAsStringAsync().Result);

                    response.EnsureSuccessStatusCode();

                    Assert.Equal(expectedTraceId.ToString(), childActivityTraceContext["TraceId"]);
                    Assert.Equal(expectedTraceState, childActivityTraceContext["TraceState"]);
                    Assert.NotEqual(expectedParentSpanId.ToString(), childActivityTraceContext["ParentSpanId"]); // there is a new activity created in instrumentation therefore the ParentSpanId is different that what is provided in the headers

                    // Test Baggage Context Propagation
                    request = new HttpRequestMessage(HttpMethod.Get, "/api/GetChildActivityBaggageContext");

                    response = await client.SendAsync(request);

                    var childActivityBaggageContext = JsonConvert.DeserializeObject <IReadOnlyDictionary <string, string> >(response.Content.ReadAsStringAsync().Result);

                    response.EnsureSuccessStatusCode();

                    Assert.Single(childActivityBaggageContext, item => item.Key == "key1" && item.Value == "value1");
                    Assert.Single(childActivityBaggageContext, item => item.Key == "key2" && item.Value == "value2");
                }
            }
            finally
            {
                OpenTelemetrySdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator(new TextMapPropagator[]
                {
                    new TraceContextPropagator(),
                    new BaggagePropagator(),
                }));
            }
        }
        public void TracerSdkSetsActivitySamplingResultBasedOnSamplingDecision()
        {
            var testSampler = new TestSampler();

            using var activitySource = new ActivitySource(ActivitySourceName);
            using var sdk            = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                       .AddSource(ActivitySourceName)
                                       .SetSampler(testSampler)
                                       .Build();

            testSampler.SamplingAction = (samplingParameters) =>
            {
                return(new SamplingResult(SamplingDecision.RecordAndSample));
            };

            using (var activity = activitySource.StartActivity("root"))
            {
                Assert.NotNull(activity);
                Assert.True(activity.IsAllDataRequested);
                Assert.True(activity.Recorded);
            }

            testSampler.SamplingAction = (samplingParameters) =>
            {
                return(new SamplingResult(SamplingDecision.RecordOnly));
            };

            using (var activity = activitySource.StartActivity("root"))
            {
                // Even if sampling returns false, for root activities,
                // activity is still created with PropagationOnly.
                Assert.NotNull(activity);
                Assert.True(activity.IsAllDataRequested);
                Assert.False(activity.Recorded);
            }

            testSampler.SamplingAction = (samplingParameters) =>
            {
                return(new SamplingResult(SamplingDecision.Drop));
            };

            using (var activity = activitySource.StartActivity("root"))
            {
                // Even if sampling returns false, for root activities,
                // activity is still created with PropagationOnly.
                Assert.NotNull(activity);
                Assert.False(activity.IsAllDataRequested);
                Assert.False(activity.Recorded);

                using (var innerActivity = activitySource.StartActivity("inner"))
                {
                    // This is not a root activity.
                    // If sampling returns false, no activity is created at all.
                    Assert.Null(innerActivity);
                }
            }
        }
        public void CreateSpan_Sampled()
        {
            using var openTelemetry = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                      .AddSource("tracername")
                                      .Build();
            var span = this.tracer.StartSpan("foo");

            Assert.True(span.IsRecording);
        }
        public void GetCurrentSpanBlankWontThrowOnEnd()
        {
            using var openTelemetry = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                      .AddSource("tracername")
                                      .Build();
            var current = Tracer.CurrentSpan;

            current.End();
        }
Exemple #21
0
        public async Task HttpClientInstrumentationInjectsHeadersAsync(bool shouldEnrich)
        {
            var processor = new Mock <BaseProcessor <Activity> >();
            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;

            // 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.CreateTracerProviderBuilder()
                   .AddHttpClientInstrumentation(o =>
            {
                if (shouldEnrich)
                {
                    o.Enrich = ActivityEnrichment;
                }
            })
                   .AddProcessor(processor.Object)
                   .Build())
            {
                using var c = new HttpClient();
                await c.SendAsync(request);
            }

            Assert.Equal(5, processor.Invocations.Count); // SetParentProvider/OnStart/OnEnd/OnShutdown/Dispose called.
            var activity = (Activity)processor.Invocations[2].Arguments[0];

            Assert.Equal(ActivityKind.Client, activity.Kind);
            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 GetStatusWithNoStatusInActivity()
        {
            using var openTelemetrySdk = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                         .AddSource(ActivitySourceName)
                                         .Build();

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

            Assert.Equal(Status.Unset, activity.GetStatus());
        }
        public void GetCurrentSpan()
        {
            using var openTelemetry = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                      .AddSource("tracername")
                                      .Build();

            var span = this.tracer.StartSpan("foo");

            Tracer.WithSpan(span);

            Assert.Equal(span.Context.SpanId, Tracer.CurrentSpan.Context.SpanId);
            Assert.True(Tracer.CurrentSpan.Context.IsValid);
        }
        public void SetCancelledStatus()
        {
            using var openTelemetrySdk = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                         .AddSource(ActivitySourceName)
                                         .Build();

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

            Assert.True(activity.GetStatus().StatusCode.Equals(Status.Error.StatusCode));
        }
        public void Tracer_StartActiveSpan_FromParent_BadArgs_NullSpanName()
        {
            using var openTelemetry = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                      .AddSource("tracername")
                                      .Build();

            var span1 = this.tracer.StartActiveSpan(null, SpanKind.Client, TelemetrySpan.NoopInstance);

            Assert.Null(span1.Activity.DisplayName);

            var span2 = this.tracer.StartActiveSpan(null, SpanKind.Client, TelemetrySpan.NoopInstance, default);

            Assert.Null(span2.Activity.DisplayName);
        }
        public void StackExchangeRedis_BadArgs()
        {
            TracerProviderBuilder builder = null;

            Assert.Throws <ArgumentNullException>(() => builder.AddRedisInstrumentation(null));

            var activityProcessor = new Mock <BaseProcessor <Activity> >();

            Assert.Throws <ArgumentNullException>(() =>
                                                  OpenTelemetrySdk.CreateTracerProviderBuilder()
                                                  .AddProcessor(activityProcessor.Object)
                                                  .AddRedisInstrumentation(null)
                                                  .Build());
        }
        public void LastSetStatusWins()
        {
            using var openTelemetrySdk = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                         .AddSource(ActivitySourceName)
                                         .Build();

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

            Assert.Equal(Status.Ok, activity.GetStatus());
        }
        public RedisProfilerEntryToActivityConverterTests()
        {
            var connectionOptions = new ConfigurationOptions
            {
                AbortOnConnectFail = false,
            };

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

            this.connection = ConnectionMultiplexer.Connect(connectionOptions);

            this.sdk = OpenTelemetrySdk.CreateTracerProviderBuilder()
                       .AddRedisInstrumentation(this.connection)
                       .Build();
        }
    public static void Main()
    {
        using var tracerProvider = OpenTelemetrySdk.CreateTracerProviderBuilder()
                                   .SetSampler(new AlwaysOnSampler())
                                   .AddSource("MyCompany.MyProduct.MyLibrary")
                                   .AddConsoleExporter()
                                   .Build();

        using (var activity = MyActivitySource.StartActivity("SayHello"))
        {
            activity?.SetTag("foo", 1);
            activity?.SetTag("bar", "Hello, World!");
            activity?.SetTag("baz", new int[] { 1, 2, 3 });
        }
    }
        public void SdkProcessesLegacyActivityWhenActivitySourceIsUpdatedWithAddSource()
        {
            using TestActivityProcessor testActivityProcessor = new TestActivityProcessor();

            bool startCalled = false;
            bool endCalled   = false;

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

            testActivityProcessor.EndAction =
                (a) =>
            {
                Assert.False(OpenTelemetrySdk.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 = OpenTelemetrySdk.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
        }