예제 #1
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
            var configuration = BuildAppConfiguration();

            services.AddHostedService <WorkerBackgroundService>();

            services.AddSingleton(new ConnectionFactory
            {
                HostName    = configuration["RabbitMq:HostName"],
                Port        = configuration.GetValue <int>("RabbitMq:Port"),
                UserName    = configuration["RabbitMq:UserName"],
                Password    = configuration["RabbitMq:Password"],
                VirtualHost = configuration["RabbitMq:VirtualHost"]
            });

            services.AddOpenTelemetryTracing(config => config
                                             .SetResourceBuilder(ResourceBuilder
                                                                 .CreateDefault()
                                                                 .AddService(nameof(WorkerBackgroundService)))
                                             .AddSource(nameof(WorkerBackgroundService))
                                             .AddZipkinExporter(o =>
            {
                o.Endpoint = new Uri(configuration["Zipkin:Url"]);
            })
                                             );
        });
        public static IServiceCollection AddOpenTelemetryExtension(this IServiceCollection services, 
            IConfiguration configuration,
            IWebHostEnvironment webHostEnvironment)
        {
            if (string.Equals(configuration["OpenTelemetryConfig:Enabled"], "true", StringComparison.OrdinalIgnoreCase))
            {
                var otlpReceiverUri = configuration["OpenTelemetryConfig:OtlpReceiverUri"];

                services.AddOpenTelemetryTracing(
                            builder =>
                            {
                                builder.SetResourceBuilder(ResourceBuilder
                                       .CreateDefault()
                                       .AddService(webHostEnvironment.ApplicationName))
                                       .AddAspNetCoreInstrumentation()
                                       .AddOtlpExporter(options => options.Endpoint = new Uri(otlpReceiverUri));

                                if (webHostEnvironment.IsDevelopment())
                                {
                                    builder.AddConsoleExporter(options => options.Targets = ConsoleExporterOutputTargets.Debug);
                                }
                            });
            }

            return services;
        }
        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 = Sdk.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.");
            System.Console.ReadLine();

            return(null);
        }
예제 #4
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureServices((builder, services) =>
        {
            services.AddSingleton <ReliablePaymentClient>();
            services.AddDbContext <FinanceContext>(options =>
                                                   options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

            services.AddOpenTelemetryTracing(config => config
                                             .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(EndpointName))
                                             .AddZipkinExporter(o =>
            {
                o.Endpoint = new Uri("http://localhost:9411/api/v2/spans");
            })
                                             .AddJaegerExporter(c =>
            {
                c.AgentHost = "localhost";
                c.AgentPort = 6831;
            })
                                             .AddHttpClientInstrumentation()
                                             .AddNServiceBusInstrumentation()
                                             .AddSqlClientInstrumentation(opt => opt.SetDbStatementForText = true)
                                             );
        })
        .UseNServiceBus(context =>
        {
            var endpoint = new EndpointConfiguration(EndpointName);
            endpoint.Configure();

            return(endpoint);
        });
예제 #5
0
        public void TestAddDetector()
        {
            Environment.SetEnvironmentVariable("AWS_REGION", "us-east-1");
            Environment.SetEnvironmentVariable("AWS_LAMBDA_FUNCTION_NAME", "testfunction");
            Environment.SetEnvironmentVariable("AWS_LAMBDA_FUNCTION_VERSION", "latest");

            using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                                       .SetResourceBuilder(ResourceBuilder
                                                           .CreateDefault()
                                                           .AddDetector(new AWSLambdaResourceDetector())) // use lambda resource detector here as it doesn't require sending identical http request to aws endpoint
                                       .Build();

            var resource           = tracerProvider.GetResource();
            var resourceAttributes = resource.Attributes.ToDictionary(x => x.Key, x => x.Value);

            Assert.Equal("aws", resourceAttributes[AWSSemanticConventions.AttributeCloudProvider]);
            Assert.Equal("aws_lambda", resourceAttributes[AWSSemanticConventions.AttributeCloudPlatform]);
            Assert.Equal("us-east-1", resourceAttributes[AWSSemanticConventions.AttributeCloudRegion]);
            Assert.Equal("testfunction", resourceAttributes[AWSSemanticConventions.AttributeFaasName]);
            Assert.Equal("latest", resourceAttributes[AWSSemanticConventions.AttributeFaasVersion]);

            Environment.SetEnvironmentVariable("AWS_REGION", null);
            Environment.SetEnvironmentVariable("AWS_LAMBDA_FUNCTION_NAME", null);
            Environment.SetEnvironmentVariable("AWS_LAMBDA_FUNCTION_VERSION", null);
        }
        public static OtlpResource.Resource ToOtlpResource(this Resource resource)
        {
            var processResource = new OtlpResource.Resource();

            foreach (KeyValuePair <string, object> attribute in resource.Attributes)
            {
                var oltpAttribute = attribute.ToOtlpAttribute();
                if (oltpAttribute != null)
                {
                    processResource.Attributes.Add(oltpAttribute);
                }
            }

            if (!processResource.Attributes.Any(kvp => kvp.Key == ResourceSemanticConventions.AttributeServiceName))
            {
                var serviceName = (string)ResourceBuilder.CreateDefault().Build().Attributes.FirstOrDefault(
                    kvp => kvp.Key == ResourceSemanticConventions.AttributeServiceName).Value;
                processResource.Attributes.Add(new OtlpCommon.KeyValue
                {
                    Key   = ResourceSemanticConventions.AttributeServiceName,
                    Value = new OtlpCommon.AnyValue {
                        StringValue = serviceName
                    },
                });
            }

            return(processResource);
        }
예제 #7
0
        public static ActivitySourceWrapper CreateTrace(string name)
        {
            var traceName = TraceSettings.TraceName(name);

            if (TraceSettings.Enabled)
            {
                var openTelemetry = Sdk.CreateTracerProviderBuilder()
                                    .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(traceName))
                                    .AddSource(traceName, traceName)
                                    .AddJaegerExporter(o =>
                {
                    o.AgentHost = TraceSettings.Host;
                    o.AgentPort = TraceSettings.Port;

                    // Examples for the rest of the options, defaults unless otherwise specified
                    // Omitting Process Tags example as Resource API is recommended for additional tags
                    o.MaxPayloadSizeInBytes = 4096;

                    // Using Batch Exporter (which is default)
                    // The other option is ExportProcessorType.Simple
                    o.ExportProcessorType         = ExportProcessorType.Batch;
                    o.BatchExportProcessorOptions = new BatchExportProcessorOptions <Activity>()
                    {
                        MaxQueueSize = 16384,
                        ScheduledDelayMilliseconds  = 5000,
                        ExporterTimeoutMilliseconds = 30000,
                        MaxExportBatchSize          = 2048,
                    };
                })
                                    .Build();
            }
            return(new ActivitySourceWrapper(new ActivitySource(traceName)));
        }
예제 #8
0
        public static IServiceCollection AddTracing(this IServiceCollection services, IWebHostEnvironment environment, IConfiguration configuration)
        {
            string agentHost;
            int    agentPort;

            if (environment.IsLocal())
            {
                agentHost = configuration["Jaeger:AgentHost"];
                agentPort = int.Parse(configuration["Jaeger:AgentPort"]);
            }
            else
            {
                agentHost = EnvironmentVariableHelper.Get("Jaeger:AgentHost", configuration);
                agentPort = int.Parse(EnvironmentVariableHelper.Get("Jaeger:AgentPort", configuration));
            }

            var connection  = ConnectionMultiplexer.Connect(EnvironmentVariableHelper.Get("Redis:Endpoint", configuration));
            var serviceName = $"{environment.ApplicationName}-{environment.EnvironmentName}";

            services.AddOpenTelemetryTracing(builder =>
            {
                builder.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName))
                .AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation()
                .AddRedisInstrumentation(connection)
                .AddJaegerExporter(options =>
                {
                    options.AgentHost = agentHost;
                    options.AgentPort = agentPort;
                })
                .SetSampler(new AlwaysOnSampler());
            });

            return(services);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSwaggerGen();

            services.AddSingleton <IConnectionMultiplexer>(ConnectionMultiplexer.Connect(Configuration.GetConnectionString("Redis")));

            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            services.AddOpenTelemetryTracing((serviceProvider, builder) =>
            {
                builder
                .SetResourceBuilder(ResourceBuilder.CreateDefault()
                                    .AddService("Service B")
                                    .AddAttributes(new[] { new KeyValuePair <string, object>("deployment.environment", Environment.EnvironmentName) }))
                .AddAspNetCoreInstrumentation(options =>
                {
                    options.RecordException = true;
                })
                .AddHttpClientInstrumentation()
                .AddSqlClientInstrumentation(options =>
                {
                    options.SetDbStatementForText            = true;
                    options.SetDbStatementForStoredProcedure = true;
                    options.RecordException = true;
                })
                .AddRedisInstrumentation(serviceProvider.GetService <IConnectionMultiplexer>())
                .AddOtlpExporter(options =>
                {
                    options.Endpoint = new Uri(Configuration.GetValue <string>("OpenTelemetryCollector"));
                });
            });
        }
예제 #10
0
 // This method gets called by the runtime. Use this method to add services to the container.
 // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
 public void ConfigureServices(IServiceCollection services)
 {
     Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator(new TextMapPropagator[]
     {
         new TraceContextPropagator(),
         new B3Propagator(),
         new BaggagePropagator(),
     }));
     services.AddActors(options =>
     {
         options.JsonSerializerOptions = new JsonSerializerOptions {
             IncludeFields = true
         };
         options.Actors.RegisterActor <Battlefield>();
     });
     services.AddOpenTelemetryTracing(b =>
     {
         b
         .AddSource("battlefield")
         .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName: "battlefield"))
         .AddHttpClientInstrumentation()
         .AddAspNetCoreInstrumentation()
         .AddOtlpExporter(opt =>
         {
             opt.Endpoint = new Uri("http://zipkin-apm-collector-collector.monitoring.svc.cluster.local:4317");// Should parametrize this
         });
         //.AddConsoleExporter();
     });
 }
예제 #11
0
        public static void Main()
        {
            using var host = WebApp.Start(
                      "http://localhost:9000",
                      appBuilder =>
            {
                // Add OpenTelemetry early in the pipeline to start timing
                // the request as soon as possible.
                appBuilder.UseOpenTelemetry();

                HttpConfiguration config = new HttpConfiguration();

                config.MessageHandlers.Add(new ActivityDisplayNameRouteEnrichingHandler());

                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional });

                appBuilder.UseWebApi(config);
            });

            using var openTelemetry = Sdk.CreateTracerProviderBuilder()
                                      .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("Owin-Example"))
                                      .AddOwinInstrumentation()
                                      .AddConsoleExporter()
                                      .Build();

            Console.WriteLine("Service listening. Press enter to exit.");
            Console.ReadLine();
        }
예제 #12
0
    public static void Main()
    {
        using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                                   .SetSampler(new AlwaysOnSampler())
                                   .AddSource("HelloWorld")
                                   .SetResourceBuilder(ResourceBuilder
                                                       .CreateDefault().AddService("getting-started")
                                                       .AddAttributes(new [] {
            new KeyValuePair <string, object>("appId", "hello-world"),
            new KeyValuePair <string, object>("deploymentId", "prod"),
        })
                                                       )
                                   .AddOtlpExporter(opt => {
            // 55680 == gRPC port for OTEL collector
            opt.Endpoint = new Uri("http://localhost:55680");
        })
                                   .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 override void Configure(IFunctionsHostBuilder builder)
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            Activity.DefaultIdFormat = ActivityIdFormat.W3C;


            var openTelemetry = Sdk.CreateTracerProviderBuilder()
                                .AddSource("Shabuhabs.AzureFunctions")
                                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("Foo"))
                                // .AddHttpClientInstrumentation()
                                //
                                //  .AddInstrumentation((options) => { options.TextFormat = new B3Format(); })
                                .AddOtlpExporter(opt => {
                opt.Endpoint            = new System.Uri("http://40.78.131.7:4317");
                opt.ExportProcessorType = ExportProcessorType.Simple;
                //opt.Headers = "X-SF-TOKEN=WH8RxYYkZrSzyYF803n8PQ";
            })

                                /*
                                 * .AddJaegerExporter(jaegerOptions =>
                                 *  {
                                 *      jaegerOptions.AgentHost = "192.168.0.110";
                                 *      jaegerOptions.AgentPort =6831;
                                 *  })
                                 */
                                .AddConsoleExporter()
                                .Build();

            builder.Services.AddSingleton(openTelemetry);
        }
예제 #14
0
    public static async Task Main()
    {
        Log.Logger = new LoggerConfiguration().WriteTo.Console(outputTemplate: ConsoleOutputTemplate)
                     .MinimumLevel.Verbose()
                     .Enrich.WithProperty("ApplicationName", AppName)
                     .CreateBootstrapLogger();
        // Add Open Telemetry
        using var openTelemetry = Sdk.CreateTracerProviderBuilder()
                                  .AddSource("Twilight.CQRS", "Twilight.Samples.CQRS", "Twilight.CQRS.Messaging.InMemory.Autofac")
                                  .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("twilight-samples-cqrs"))
                                  .AddConsoleExporter()
                                  .Build();

        Log.Information("Running {AppName}", AppName);

        try
        {
            await CreateHostBuilder().RunConsoleAsync();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "{AppName} terminated unexpectedly. CqrsMessage: {ExceptionMessage}", AppName, ex.Message);

            Environment.Exit(-1);
        }
        finally
        {
            Log.Information("Stopped {AppName}", AppName);
            Log.CloseAndFlush();

            Environment.Exit(0);
        }
    }
예제 #15
0
        private static void ConfigureOpenTelemetry(TracerProviderBuilder builder, ICartStore cartStore)
        {
            builder.AddAspNetCoreInstrumentation();

            if (cartStore is RedisCartStore redisCartStore)
            {
                builder.AddRedisInstrumentation(redisCartStore.ConnectionMultiplexer);
            }

            var exportType  = Environment.GetEnvironmentVariable("EXPORT_TYPE") ?? "jaeger";
            var serviceName = "CartService" + (exportType == "jaeger" ? string.Empty : $"-{exportType}");

            builder.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName, null, null, false, $"{exportType}-{Guid.NewGuid().ToString()}"));

            switch (exportType)
            {
            case "otlp":
                var otlpEndpoint = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_SPAN_ENDPOINT")
                                   ?? Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT");
                builder
                .AddOtlpExporter(options => options.Endpoint = otlpEndpoint);
                break;

            case "jaeger":
            default:

                builder.AddAspNetCoreInstrumentation().AddJaegerExporter();
                Console.WriteLine("Jaeger Tracing completed");
                break;
            }
        }
예제 #16
0
        public static TracerProvider EnableTracing(Jaeger config)
        {
            TracerProvider tracing = null;

            if (config.Enabled)
            {
                tracing = Sdk.CreateTracerProviderBuilder()
                          .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("p2g"))
                          .AddHttpClientInstrumentation(config =>
                {
                    config.RecordException = true;
                    config.Enrich          = (activity, name, rawEventObject) =>
                    {
                        activity.SetTag(TagKey.App, TagValue.P2G);
                        activity.SetTag("SpanId", activity.SpanId);
                        activity.SetTag("TraceId", activity.TraceId);
                    };
                })
                          .AddSource("P2G")
                          .AddJaegerExporter(o =>
                {
                    o.AgentHost = config.AgentHost;
                    o.AgentPort = config.AgentPort.GetValueOrDefault();
                })
                          .Build();

                Log.Information("Tracing started and exporting to: http://{@Host}:{@Port}", config.AgentHost, config.AgentPort);
            }

            return(tracing);
        }
예제 #17
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .UseMicrosoftLogFactoryLogging()
        .UseNServiceBus(hostBuilderContext =>
        {
            var endpointConfiguration = new EndpointConfiguration(EndpointName);

            endpointConfiguration.UseSerialization <SystemJsonSerializer>();

            var transport = endpointConfiguration.UseTransport <RabbitMQTransport>();
            transport.ConnectionString("host=localhost");
            transport.UseConventionalRoutingTopology();

            var routing = transport.Routing();
            routing.RouteToEndpoint(typeof(MakeItYell).Assembly, "NsbActivities.ChildWorkerService");

            endpointConfiguration.UsePersistence <LearningPersistence>();

            endpointConfiguration.EnableInstallers();

            endpointConfiguration.AuditProcessedMessagesTo("NsbActivities.Audit");

            endpointConfiguration.AuditSagaStateChanges("Particular.ServiceControl.2");

            endpointConfiguration.PurgeOnStartup(true);

            var settings = endpointConfiguration.GetSettings();

            settings.Set(new NServiceBus.Extensions.Diagnostics.InstrumentationOptions
            {
                CaptureMessageBody = true
            });

            // configure endpoint here
            return(endpointConfiguration);
        })
        .ConfigureServices((_, services) =>
        {
            services.AddOpenTelemetryTracing(builder => builder
                                             .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(EndpointName))
                                             .AddNServiceBusInstrumentation()
                                             .AddHttpClientInstrumentation()
                                             .AddAspNetCoreInstrumentation()
                                             .AddZipkinExporter(o =>
            {
                o.Endpoint = new Uri("http://localhost:9411/api/v2/spans");
            })
                                             .AddJaegerExporter(c =>
            {
                c.AgentHost = "localhost";
                c.AgentPort = 6831;
            })
                                             );

            services.AddScoped <Func <HttpClient> >(s => () => new HttpClient
            {
                BaseAddress = new Uri("https://localhost:5001")
            });
        })
        ;
        internal static object RunWithActivity(string host, int port)
        {
            // Enable OpenTelemetry for the sources "Samples.SampleServer" and "Samples.SampleClient"
            // and use the Jaeger exporter.
            using var openTelemetry = Sdk.CreateTracerProviderBuilder()
                                      .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("jaeger-test"))
                                      .AddSource("Samples.SampleClient", "Samples.SampleServer")
                                      .AddJaegerExporter(o =>
            {
                o.AgentHost = host;
                o.AgentPort = port;
            })
                                      .Build();

            // The above lines are 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 Jaeger in the background. Use Jaeger to view them." +
                                         "Press ENTER to stop.");
                System.Console.ReadLine();
            }

            return(null);
        }
예제 #19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            var redis = new Redis(Environment.GetEnvironmentVariable("REDIS_ADDRESS"));

            redis.InitializeAsync().GetAwaiter().GetResult();

            services.AddSingleton <Redis>(redis);

            services.AddOpenTelemetryTracing(builder => {
                builder
                .SetResourceBuilder(
                    ResourceBuilder
                    .CreateDefault()
                    .AddService("aspnetcore-webapi"))
                .AddAspNetCoreInstrumentation()
                .AddRedisInstrumentation(redis.ConnectionMultiplexer)
                .AddOtlpExporter(options => {
                    options.Endpoint = new Uri(Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT"));
                });
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "AspNetCoreWebApi", Version = "v1"
                });
            });
        }
        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 = Sdk.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);
        }
예제 #21
0
        /// <summary>
        /// Configures OpenTelemetry tracing.
        /// </summary>
        /// <param name="services">The service collection to add forward proxies into.</param>
        public void ConfigureTracing(IServiceCollection services)
        {
            this.Logger.LogDebug("Setting up OpenTelemetry");
            OpenTelemetryConfig config = new OpenTelemetryConfig();

            this.configuration.GetSection("OpenTelemetry").Bind(config);
            if (config.Enabled)
            {
                services.AddOpenTelemetryTracing(builder =>
                {
                    builder.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(config.ServiceName))
                    .AddAspNetCoreInstrumentation(options =>
                    {
                        options.Filter = (httpContext) =>
                        {
                            return(!config.IgnorePathPrefixes.Any(s => httpContext.Request.Path.ToString().StartsWith(s, StringComparison.OrdinalIgnoreCase)));
                        };
                    })
                    .AddHttpClientInstrumentation()
                    .AddSource(config.Sources);
                    if (config.ZipkinEnabled)
                    {
                        builder.AddZipkinExporter(options =>
                        {
                            options.Endpoint = config.ZipkinUri;
                        });
                    }

                    if (config.ConsoleEnabled)
                    {
                        builder.AddConsoleExporter();
                    }
                });
            }
        }
예제 #22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "CurrencyConversionService", Version = "v1"
                });
            });

            services.AddHostedService <BankScraperBackgroundService>();

            var serviceName = nameof(CurrencyConversionService);

            services.AddOpenTelemetryTracing((builder)
                                             => builder
                                             .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName))
                                             .AddSource(serviceName)
                                             .AddAspNetCoreInstrumentation()
                                             .AddHttpClientInstrumentation()
                                             .SetSampler(new AlwaysOnSampler())
                                             .AddJaegerExporter(options =>
            {
                options.AgentHost             = "localhost";
                options.AgentPort             = 6831;
                options.MaxPayloadSizeInBytes = 65000;
            }));
        }
        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 = Sdk.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);
        }
예제 #24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "FirstApi", Version = "v1"
                });
            });
            services.AddHttpClient();

            services.AddOpenTelemetryTracing((b) =>
            {
                b
                .SetSampler(new AlwaysOnSampler())
                .AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation()
                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("TelemetryApp.FirstApi"))
                .AddJaegerExporter(o =>
                {
                    o.AgentHost = Configuration["Settings:JaegerHost"];
                    o.AgentPort = 6831;
                });
            });
        }
예제 #25
0
        private static object RunWithActivitySource()
        {
            // Enable OpenTelemetry for the sources "Samples.SampleServer" and "Samples.SampleClient"
            // and use Console exporter.
            using var tracerProvider = Sdk.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);
        }
예제 #26
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureLogging(loggingBuilder =>
        {
            loggingBuilder.ClearProviders();
            loggingBuilder.AddConsole();

            loggingBuilder
            .AddOpenTelemetry(options =>
            {
                options.IncludeFormattedMessage = true;
                options.IncludeScopes           = true;
                options.ParseStateValues        = true;

                options
                .SetResourceBuilder(
                    ResourceBuilder
                    .CreateDefault()
                    .AddService("OpenTelemetry-Dotnet-Example")
                    .AddAttributes(new Dictionary <string, object> {
                    { "environment", "production" }
                })
                    .AddTelemetrySdk())
                .AddOtlpExporter(options =>
                {
                    options.Endpoint = new Uri($"{Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT")}");
                    options.Headers  = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_HEADERS");
                });
            });
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup <Startup>();
        });
예제 #27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddOpenTelemetryTracing((builder) =>
            {
                builder
                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(Configuration.GetValue <string>("Jaeger:ServiceName")))
                .AddHttpClientInstrumentation()
                .AddAspNetCoreInstrumentation()
                .AddEntityFrameworkCoreInstrumentation(config => config.SetDbStatementForText = true)
                .AddJaegerExporter(config =>
                {
                    Configuration.GetSection("Jaeger").Bind(config);
                });
            });
            //it doesn's work ,so use 'Bind'
            services.Configure <JaegerExporterOptions>(Configuration.GetSection("Jaeger"));
            services.AddLogDashboard();
            //启动配置
            services.AddAutoMapperSetup();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "DDD project", Version = "v1"
                });
            });
            services.AddMediatR(typeof(Startup), typeof(Example.Domain.CommandHandlers.CommandHandler));

            NativeInjectorBootStrapper.RegisterServices(services, Configuration);
        }
예제 #28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(logging =>
            {
                logging.AddSeq($"http://{Configuration.GetConnectionString("seq")}")
                .AddSimpleConsole(o => o.IncludeScopes = true);
            });
            services.AddOpenTelemetryTracing(tracing =>
            {
                tracing
                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(typeof(Startup).Assembly.GetName().Name))
                .AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation()
                .AddGrpcClientInstrumentation()
                .SetSampler(new AlwaysOnSampler())
                .AddZipkinExporter(options =>
                {
                    options.Endpoint = new Uri($"http://{Configuration.GetConnectionString("zipkin")}/api/v2/spans");
                });
            });

            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddGrpcClient <Trivia.TriviaClient>(options =>
            {
                options.Address = GetUri(Configuration, "TriviaServer");
            });
        }
예제 #29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddHttpContextAccessor();
            services.AddHttpClient();

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .WriteTo.File(new CompactJsonFormatter(), @"C:\temp\testlog\log.json", shared: true)
                         .MinimumLevel.Error()
                         .CreateLogger();

            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));
            services.AddOpenTelemetryTracing(tracing =>
            {
                tracing.AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation()
                .SetSampler(new AlwaysOnSampler())
                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(typeof(Startup).Assembly.GetName().Name))
                .AddZipkinExporter(options =>
                {
                    options.Endpoint = new Uri("http://localhost:9411/api/v2/spans");
                });
            });
        }
예제 #30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddGrpc();
            services.AddGrpcReflection();
            services.AddSingleton <IComputeStepImpl, DummyStep>();

            services.AddSingleton(new ActivitySource("Workflows"));

            // This one creates a singleton of the type TracerProvider.
            services.AddOpenTelemetryTracing((builder) =>
            {
                builder
                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("ComputeStep"))
                .AddSource("Workflows")
                // For incoming requests
                .AddAspNetCoreInstrumentation()
                // For outgoing requests
                .AddGrpcClientInstrumentation()
                .AddHttpClientInstrumentation()
                // Export everything to the console.
                // .AddConsoleExporter();
                .AddJaegerExporter(o =>
                {
                    o.AgentHost             = Configuration["NODE_IP"];
                    o.MaxPayloadSizeInBytes = 65000;
                });
            });

            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });
        }