コード例 #1
0
ファイル: Startup.cs プロジェクト: MCGPPeters/Radix
    public override void Configure(IFunctionsHostBuilder builder)
    {
        var configuration = builder.GetContext().Configuration;

        var result =
            from indexName in SearchIndexName.Create(configuration[Constants.SearchIndexName])
            from searchServiceName in SearchServiceName.Create(configuration[Constants.SearchServiceName])
            from searchApiKey in SearchApiKey.Create(configuration[Constants.SearchApiKey])
            let serviceEndpoint = new Uri($"https://{searchServiceName}.search.windows.net/")
                                  let credentials = new Azure.AzureKeyCredential(searchApiKey)
                                                    select new SearchClient(serviceEndpoint, indexName, credentials);

        switch (result)
        {
        case Valid <SearchClient>(var searchClient):
            builder.Services.AddSingleton(searchClient);
            break;

        case Invalid <SearchClient>(var errors):
            throw new Exception(errors.Aggregate <string, Concat>());

        default:
            break;
        }

        builder.Services.AddSingleton(serviceProvider =>
        {
            IPlaywright?playwright = Playwright.CreateAsync().GetAwaiter().GetResult();
            return(playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions {
                Timeout = 0
            }).GetAwaiter().GetResult());
        });

        builder.Services.AddSingleton(serviceProvider =>
        {
            var browser = serviceProvider.GetService <IBrowser>();
            return(browser.NewContextAsync(new BrowserNewContextOptions {
                IgnoreHTTPSErrors = true
            }).GetAwaiter().GetResult());
        });

        var openTelemetry = Sdk.CreateTracerProviderBuilder()
                            .AddSource("Radix.Shop.Catalog.Crawling.Jumbo")
                            .AddAspNetCoreInstrumentation()
                            //.AddHttpClientInstrumentation()
                            // .SetSampler(new AlwaysOnSampler())
                            .AddConsoleExporter()
                            .Build();

        builder.Services.AddSingleton(openTelemetry);
    }
コード例 #2
0
        public void LastSetStatusWins()
        {
            using var tracerProvider = Sdk.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());
        }
コード例 #3
0
        public async Task CustomPropagator()
        {
            var activityProcessor = new Mock <BaseProcessor <Activity> >();

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

            var propagator = new Mock <IPropagator>();

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

            // Arrange
            using (var testFactory = this.factory
                                     .WithWebHostBuilder(builder =>
                                                         builder.ConfigureTestServices(services =>
            {
                this.openTelemetrySdk = Sdk.CreateTracerProviderBuilder()
                                        .AddAspNetCoreInstrumentation((opt) => opt.Propagator = propagator.Object)
                                        .AddProcessor(activityProcessor.Object)
                                        .Build();
            })))
            {
                using var client = testFactory.CreateClient();
                var response = await client.GetAsync("/api/values/2");

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

                WaitForProcessorInvocations(activityProcessor, 2);
            }

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

            Assert.Equal("ActivityCreatedByHttpInListener", activity.OperationName);

            Assert.Equal(ActivityKind.Server, activity.Kind);
            Assert.True(activity.Duration != TimeSpan.Zero);
            Assert.Equal("api/Values/{id}", activity.DisplayName);
            Assert.Equal("/api/values/2", activity.GetTagValue(SpanAttributeConstants.HttpPathKey) as string);

            Assert.Equal(expectedTraceId, activity.Context.TraceId);
            Assert.Equal(expectedSpanId, activity.ParentSpanId);
        }
コード例 #4
0
        public void StackExchangeRedis_BadArgs()
        {
            TracerProviderBuilder builder = null;

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

            var activityProcessor = new Mock <ActivityProcessor>();

            Assert.Throws <ArgumentNullException>(() =>
                                                  Sdk.CreateTracerProviderBuilder()
                                                  .AddProcessor(activityProcessor.Object)
                                                  .AddRedisInstrumentation(null)
                                                  .Build());
        }
コード例 #5
0
        public void Tracer_StartActiveSpan_FromParent_BadArgs_NullSpanName()
        {
            using var openTelemetry = Sdk.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);
        }
コード例 #6
0
        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 = Sdk.CreateTracerProviderBuilder()
                                      .AddZipkinExporter(o =>
            {
                o.Endpoint = new Uri(zipkinUri);
            })
                                      .AddRedisInstrumentation(connection, options =>
            {
                // changing flushinterval from 10s to 5s
                options.FlushInterval = TimeSpan.FromSeconds(5);
            })
                                      .AddSource("redis-test")
                                      .Build();

            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);
                }
            }

            System.Console.Write("Press ENTER to stop.");
            System.Console.ReadLine();

            return(null);
        }
コード例 #7
0
        public void LastSetStatusWins()
        {
            using var openTelemetrySdk = Sdk.CreateTracerProviderBuilder()
                                         .AddSource(ActivitySourceName)
                                         .Build();

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

            Assert.True(activity.GetStatus().IsOk);
        }
コード例 #8
0
        public static async Task Main()
        {
            using var openTelemetry = Sdk.CreateTracerProviderBuilder()
                                      .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("Wcf-Client"))
                                      .AddWcfInstrumentation()
                                      .AddZipkinExporter()
                                      .Build();

            await CallService("StatusService_Http").ConfigureAwait(false);
            await CallService("StatusService_Tcp").ConfigureAwait(false);

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }
コード例 #9
0
        public void SuccessfulCommandTest(
            CommandType commandType,
            string commandText,
            bool captureStoredProcedureCommandName,
            bool captureTextCommandContent = false,
            bool isFailure    = false,
            bool shouldEnrich = true)
        {
            var activityProcessor = new Mock <BaseProcessor <Activity> >();

            using var shutdownSignal = Sdk.CreateTracerProviderBuilder()
                                       .AddProcessor(activityProcessor.Object)
                                       .AddSqlClientInstrumentation(options =>
            {
                options.SetStoredProcedureCommandName = captureStoredProcedureCommandName;
                options.SetTextCommandContent         = captureTextCommandContent;
                if (shouldEnrich)
                {
                    options.Enrich = ActivityEnrichment;
                }
            })
                                       .Build();

            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(3, activityProcessor.Invocations.Count);

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

            VerifyActivityData(commandType, commandText, captureStoredProcedureCommandName, captureTextCommandContent, isFailure, dataSource, activity);
        }
コード例 #10
0
    public static void Main()
    {
        using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                                   .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 });
        }
    }
コード例 #11
0
        public void DefaultResourceGetsAssociatedWithActivityIfNoneConfigured()
        {
            using var activitySource = new ActivitySource(nameof(this.ResourceGetsAssociatedWithActivity));
            var expectedResource = Resource.Empty;

            using var openTelemetry = Sdk.CreateTracerProviderBuilder()
                                      .AddSource(nameof(this.ResourceGetsAssociatedWithActivity))
                                      .Build();

            using (var root = activitySource.StartActivity("root"))
            {
                Assert.Equal(expectedResource, root.GetResource());
            }
        }
コード例 #12
0
        public void TracerProviderSdkBuildsWithDefaultResource()
        {
            var tracerProvider = Sdk.CreateTracerProviderBuilder().Build();
            var resource       = tracerProvider.GetResource();
            var attributes     = resource.Attributes;

            Assert.NotNull(resource);
            Assert.NotEqual(Resource.Empty, resource);
            Assert.Contains(new KeyValuePair <string, object>("telemetry.sdk.name", "opentelemetry"), attributes);
            Assert.Contains(new KeyValuePair <string, object>("telemetry.sdk.language", "dotnet"), attributes);
            var versionAttribute = attributes.Where(pair => pair.Key.Equals("telemetry.sdk.version"));

            Assert.Single(versionAttribute);
        }
コード例 #13
0
        public TraceBenchmarks()
        {
            Activity.DefaultIdFormat = ActivityIdFormat.W3C;

            ActivitySource.AddActivityListener(new ActivityListener
            {
                ActivityStarted = null,
                ActivityStopped = null,
                ShouldListenTo  = (activitySource) => activitySource.Name == this.sourceWithPropagationDataListner.Name,
                Sample          = (ref ActivityCreationOptions <ActivityContext> options) => ActivitySamplingResult.PropagationData,
            });

            ActivitySource.AddActivityListener(new ActivityListener
            {
                ActivityStarted = null,
                ActivityStopped = null,
                ShouldListenTo  = (activitySource) => activitySource.Name == this.sourceWithAllDataListner.Name,
                Sample          = (ref ActivityCreationOptions <ActivityContext> options) => ActivitySamplingResult.AllData,
            });

            ActivitySource.AddActivityListener(new ActivityListener
            {
                ActivityStarted = null,
                ActivityStopped = null,
                ShouldListenTo  = (activitySource) => activitySource.Name == this.sourceWithAllDataAndRecordedListner.Name,
                Sample          = (ref ActivityCreationOptions <ActivityContext> options) => ActivitySamplingResult.AllDataAndRecorded,
            });

            Sdk.CreateTracerProviderBuilder()
            .SetSampler(new AlwaysOnSampler())
            .AddSource(this.sourceWithOneProcessor.Name)
            .AddProcessor(new DummyActivityProcessor())
            .Build();

            Sdk.CreateTracerProviderBuilder()
            .SetSampler(new AlwaysOnSampler())
            .AddSource(this.sourceWithTwoProcessors.Name)
            .AddProcessor(new DummyActivityProcessor())
            .AddProcessor(new DummyActivityProcessor())
            .Build();

            Sdk.CreateTracerProviderBuilder()
            .SetSampler(new AlwaysOnSampler())
            .AddSource(this.sourceWithThreeProcessors.Name)
            .AddProcessor(new DummyActivityProcessor())
            .AddProcessor(new DummyActivityProcessor())
            .AddProcessor(new DummyActivityProcessor())
            .Build();
        }
        public void CanEnrichActivityFromCommand(string value)
        {
            var connectionOptions = new ConfigurationOptions
            {
                AbortOnConnectFail = true,
            };

            connectionOptions.EndPoints.Add(RedisEndPoint);

            using var connection = ConnectionMultiplexer.Connect(connectionOptions);

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

            using (Sdk.CreateTracerProviderBuilder()
                   .AddProcessor(activityProcessor.Object)
                   .SetSampler(sampler)
                   .AddRedisInstrumentation(connection, c => c.Enrich = (activity, command) =>
            {
                if (command.ElapsedTime < TimeSpan.FromMilliseconds(100))
                {
                    activity.AddTag("is_fast", true);
                }
            })
                   .Build())
            {
                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(7, activityProcessor.Invocations.Count);

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

            Assert.Equal(true, setActivity.GetTagValue("is_fast"));
            var getActivity = (Activity)activityProcessor.Invocations[3].Arguments[0];

            Assert.Equal(true, getActivity.GetTagValue("is_fast"));
        }
コード例 #15
0
        public async Task SuccessfulTemplateControllerCallUsesParentContext()
        {
            var activityProcessor = new Mock <BaseProcessor <Activity> >();

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

            // Arrange
            using (var testFactory = this.factory
                                     .WithWebHostBuilder(builder =>
                                                         builder.ConfigureTestServices(services =>
            {
                this.openTelemetrySdk = Sdk.CreateTracerProviderBuilder().AddAspNetCoreInstrumentation()
                                        .AddProcessor(activityProcessor.Object)
                                        .Build();
            })))
            {
                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(activityProcessor, 2);
            }

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

#if !NETCOREAPP2_1
            // ASP.NET Core after 2.x is W3C aware and hence Activity created by it
            // must be used.
            Assert.Equal("Microsoft.AspNetCore.Hosting.HttpRequestIn", activity.OperationName);
#else
            // ASP.NET Core before 3.x is not W3C aware and hence Activity created by it
            // is always ignored and new one is created by the Instrumentation
            Assert.Equal("ActivityCreatedByHttpInListener", activity.OperationName);
#endif
            Assert.Equal(ActivityKind.Server, activity.Kind);
            Assert.Equal("api/Values/{id}", activity.DisplayName);
            Assert.Equal("/api/values/2", activity.GetTagValue(SpanAttributeConstants.HttpPathKey) as string);

            Assert.Equal(expectedTraceId, activity.Context.TraceId);
            Assert.Equal(expectedSpanId, activity.ParentSpanId);
        }
コード例 #16
0
        public void SetStatusWithIgnoredDescription()
        {
            using var openTelemetrySdk = Sdk.CreateTracerProviderBuilder()
                .AddSource(ActivitySourceName)
                .Build();

            using var source = new ActivitySource(ActivitySourceName);
            using var activity = source.StartActivity(ActivityName);
            activity.SetStatus(Status.Ok.WithDescription("This should be ignored."));
            activity?.Stop();

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

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

            this.connection = ConnectionMultiplexer.Connect(connectionOptions);

            this.sdk = Sdk.CreateTracerProviderBuilder()
                       .AddRedisInstrumentation(this.connection)
                       .Build();
        }
コード例 #18
0
        public void ResourceGetsAssociatedWithActivity()
        {
            using var activitySource = new ActivitySource(nameof(this.ResourceGetsAssociatedWithActivity));
            var expectedResource = Resources.Resources.CreateServiceResource("ServiceNameAbc");

            using var openTelemetry = Sdk.CreateTracerProviderBuilder()
                                      .AddSource(nameof(this.ResourceGetsAssociatedWithActivity))
                                      .SetResource(expectedResource)
                                      .Build();

            using (var root = activitySource.StartActivity("root"))
            {
                Assert.Equal(expectedResource, root.GetResource());
            }
        }
コード例 #19
0
        static void Main(string[] args)
        {
            var connection = ConnectionMultiplexer.Connect("localhost:6379");

            Sdk.CreateTracerProviderBuilder()
            .AddRedisInstrumentation(connection, opt => opt.FlushInterval = TimeSpan.FromSeconds(1))
            .AddConsoleExporter()
            .Build();

            var db = connection.GetDatabase();

            var msg = db.StringGet("testKey01");

            Console.WriteLine(msg);
        }
コード例 #20
0
        public void SetStatusWithDescription()
        {
            using var openTelemetrySdk = Sdk.CreateTracerProviderBuilder()
                .AddSource(ActivitySourceName)
                .Build();

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

            var status = activity.GetStatus();
            Assert.Equal(StatusCode.Error, status.StatusCode);
            Assert.Equal("Not Found", status.Description);
        }
コード例 #21
0
        private static object RunWithActivitySource(string endpoint, string protocol)
        {
            // Adding the OtlpExporter creates a GrpcChannel.
            // This switch must be set before creating a GrpcChannel 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);

            var otlpExportProtocol = ToOtlpExportProtocol(protocol);

            if (!otlpExportProtocol.HasValue)
            {
                System.Console.WriteLine($"Export protocol {protocol} is not supported. Default protocol 'grpc' will be used.");
                otlpExportProtocol = OtlpExportProtocol.Grpc;
            }

            // Enable OpenTelemetry for the sources "Samples.SampleServer" and "Samples.SampleClient"
            // and use OTLP exporter.
            using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                                       .AddSource("Samples.SampleClient", "Samples.SampleServer")
                                       .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("otlp-test"))
                                       .AddOtlpExporter(opt =>
            {
                // If endpoint was not specified, the proper one will be selected according to the protocol.
                if (!string.IsNullOrEmpty(endpoint))
                {
                    opt.Endpoint = new Uri(endpoint);
                }

                opt.Protocol = otlpExportProtocol.Value;

                System.Console.WriteLine($"OTLP Exporter is using {opt.Protocol} protocol and endpoint {opt.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);
        }
コード例 #22
0
        internal static object Run()
        {
            // Prerequisite for running this example.
            // In a separate console window, start the example
            // ASP.NET Core gRPC service by running the following command
            // from the reporoot\examples\GrpcService\.
            // (eg: C:\repos\opentelemetry-dotnet\examples\GrpcService\)
            //
            // dotnet run

            // To run this example, run the following command from
            // the reporoot\examples\Console\.
            // (eg: C:\repos\opentelemetry-dotnet\examples\Console\)
            //
            // dotnet run grpc

            using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                                       .AddGrpcClientInstrumentation()
                                       .AddSource("grpc-net-client-test")
                                       .AddConsoleExporter()
                                       .Build();

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

            using (var parent = source.StartActivity("Main", ActivityKind.Server))
            {
                using var channel = GrpcChannel.ForAddress("https://localhost:44335");
                var client = new Greeter.GreeterClient(channel);

                try
                {
                    var reply = client.SayHelloAsync(new HelloRequest {
                        Name = "GreeterClient"
                    }).GetAwaiter().GetResult();
                    System.Console.WriteLine($"Message received: {reply.Message}");
                }
                catch (RpcException)
                {
                    System.Console.Error.WriteLine($"To run this Grpc.Net.Client example, first start the Examples.GrpcService project.");
                    throw;
                }
            }

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

            return(null);
        }
コード例 #23
0
        public async Task BaggageClearedWhenActivityStopped()
        {
            int?baggageCountAfterStart = null;
            int?baggageCountAfterStop  = null;

            using EventWaitHandle stopSignal = new EventWaitHandle(false, EventResetMode.ManualReset);

            void ConfigureTestServices(IServiceCollection services)
            {
                this.tracerProvider = Sdk.CreateTracerProviderBuilder()
                                      .AddAspNetCoreInstrumentation(new AspNetCoreInstrumentation(
                                                                        new TestHttpInListener(new AspNetCoreInstrumentationOptions())
                {
                    OnStartActivityCallback = (activity, payload) =>
                    {
                        baggageCountAfterStart = Baggage.Current.Count;
                    },
                    OnStopActivityCallback = (activity, payload) =>
                    {
                        baggageCountAfterStop = Baggage.Current.Count;
                        stopSignal.Set();
                    },
                }))
                                      .Build();
            }

            // Arrange
            using (var client = this.factory
                                .WithWebHostBuilder(builder =>
                                                    builder.ConfigureTestServices(ConfigureTestServices))
                                .CreateClient())
            {
                using var request = new HttpRequestMessage(HttpMethod.Get, "/api/values");

                request.Headers.TryAddWithoutValidation("baggage", "TestKey1=123,TestKey2=456");

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

            stopSignal.WaitOne(5000);

            // Assert
            Assert.NotNull(baggageCountAfterStart);
            Assert.Equal(2, baggageCountAfterStart);
            Assert.NotNull(baggageCountAfterStop);
            Assert.Equal(0, baggageCountAfterStop);
        }
コード例 #24
0
        public async Task SuccessfulTemplateControllerCallUsesParentContext()
        {
            var activityProcessor = new Mock <BaseProcessor <Activity> >();

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

            // Arrange
            using (var testFactory = this.factory
                                     .WithWebHostBuilder(builder =>
                                                         builder.ConfigureTestServices(services =>
            {
                this.tracerProvider = Sdk.CreateTracerProviderBuilder().AddAspNetCoreInstrumentation()
                                      .AddProcessor(activityProcessor.Object)
                                      .Build();
            })))
            {
                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(activityProcessor, 3);
            }

            // List of invocations
            // 1. SetParentProvider for TracerProviderSdk
            // 2. OnStart for the activity created by AspNetCore with the OperationName: Microsoft.AspNetCore.Hosting.HttpRequestIn
            // 3. OnStart for the sibling activity created by the instrumentation library with the OperationName: Microsoft.AspNetCore.Hosting.HttpRequestIn and the first tag that is added is (IsCreatedByInstrumentation, bool.TrueString)
            // 4. OnEnd for the sibling activity created by the instrumentation library with the OperationName: Microsoft.AspNetCore.Hosting.HttpRequestIn and the first tag that is added is (IsCreatedByInstrumentation, bool.TrueString)

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

            Assert.Equal("Microsoft.AspNetCore.Hosting.HttpRequestIn", activity.OperationName);
            Assert.Equal("api/Values/{id}", activity.DisplayName);

            Assert.Equal(expectedTraceId, activity.Context.TraceId);
            Assert.Equal(expectedSpanId, activity.ParentSpanId);

            ValidateAspNetCoreActivity(activity, "/api/values/2");
        }
コード例 #25
0
        public void SdkProcessesLegacyActivityWhenActivitySourceIsUpdatedWithAddSource()
        {
            using TestActivityProcessor testActivityProcessor = new TestActivityProcessor();

            bool startCalled = false;
            bool endCalled   = false;

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

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

            var emptyActivitySource = new ActivitySource(string.Empty);

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

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

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

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

            Activity activity = new Activity(operationNameForLegacyActivity);

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

            Assert.True(startCalled); // Processor.OnStart is called since we provided the legacy OperationName
            Assert.True(endCalled);   // Processor.OnEnd is not called since the ActivitySource is updated and the updated source name is added as a Source to the provider
        }
        /// <summary>
        /// Adds OpenTelemetry TracerProvider to the specified <see cref="IServiceCollection" />.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
        /// <param name="configure">The <see cref="TracerProviderBuilder"/> action to configure TracerProviderBuilder.</param>
        /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
        public static IServiceCollection AddOpenTelemetryTracing(this IServiceCollection services, Action <IServiceProvider, TracerProviderBuilder> configure)
        {
            if (configure is null)
            {
                throw new ArgumentNullException(nameof(configure));
            }

            var builder = Sdk.CreateTracerProviderBuilder();

            services.AddOpenTelemetryTracing((sp) =>
            {
                configure(sp, builder);
                return(builder.Build());
            });
            return(services);
        }
コード例 #27
0
        public void Tracer_StartSpan_FromParentContext_BadArgs_NullSpanName()
        {
            using var openTelemetry = Sdk.CreateTracerProviderBuilder()
                                      .AddSource("tracername")
                                      .Build();

            var blankContext = default(SpanContext);

            var span1 = this.tracer.StartSpan(null, SpanKind.Client, blankContext);

            Assert.Null(span1.Activity.DisplayName);

            var span2 = this.tracer.StartSpan(null, SpanKind.Client, blankContext, default);

            Assert.Null(span2.Activity.DisplayName);
        }
コード例 #28
0
        // TODO: ADD THIS TEST AFTER IMPLEMENTING ILOGGER EXPORTER
        //public void VerifyILoggerAsTelemetryItem

        private void Setup(out BatchExportProcessor <Activity> processor, out MockTransmitter transmitter)
        {
            transmitter = new MockTransmitter();
            processor   = new BatchExportProcessor <Activity>(new AzureMonitorTraceExporter(
                                                                  options: new AzureMonitorExporterOptions
            {
                ConnectionString = EmptyConnectionString,
            },
                                                                  transmitter: transmitter));

            Sdk.CreateTracerProviderBuilder()
            .SetSampler(new AlwaysOnSampler())
            .AddSource(ActivitySourceName)
            .AddProcessor(processor)
            .Build();
        }
コード例 #29
0
        public void ThrowsInExporter()
        {
            var activityExporter = new TestActivityExporter(_ => throw new ArgumentException("123"));

            using var openTelemetry = Sdk.CreateTracerProviderBuilder()
                                      .AddSource("random")
                                      .SetSampler(new AlwaysOnSampler())
                                      .AddProcessor(new SimpleActivityProcessor(activityExporter))
                                      .Build();

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

            // does not throw
            activity.Stop();
        }
コード例 #30
0
ファイル: Program.cs プロジェクト: brucehu123/core-data
        static void Main(string[] args)
        {
            var subcriber = new CoreDataSubscriber(listener => listener.Name == DiagnosticListenerNames.DiagnosticSourceName);

            subcriber.Subscribe();

            using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                                       //.AddSqlClientInstrumentation(options =>
                                       //{
                                       //    options.Enrich = (activity, str, obj) =>
                                       //    {
                                       //        activity.SetTag(str, obj);
                                       //    };
                                       //})
                                       .AddSource(CoreDataActivitySourceHelper.ActivitySourceName)
                                       .AddSource("Demo")
                                       .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("Demo"))
                                       .AddConsoleExporter()
                                       .Build();

            var builder = new ConfigurationBuilder()
                          .SetBasePath(AppContext.BaseDirectory)
                          .AddJsonFile("appsettings.json", true);

            var configuration = builder.Build();

            var services = new ServiceCollection();

            services.AddSingleton <IConfiguration>(configuration);
            services.AddTransient <IUserRepository, UserRepository>();

            var provider = services.BuildServiceProvider();

            var activity   = source.StartActivity("DemoAct", ActivityKind.Server);
            var repository = provider.GetService <IUserRepository>();

            //repository.Add(new Domain.User() { Id = 12, Name = "test2" });
            repository.CountAsync(s => s.Id == 1).GetAwaiter().GetResult();
            activity.Stop();

            //var builder=Sdk.CreateTracerProviderBuilder().ad

            var host = new HostBuilder()
                       .Build();

            host.Run();
        }