コード例 #1
0
        /// <summary>
        /// Registers a Tracer as the global tracer, if unregistered.
        /// </summary>
        /// <param name="tracer">Existing SignalFx Tracer instance.</param>
        /// <returns>True if the Tracer was successfully registered by this call, otherwise false.</returns>
        public static bool RegisterGlobalTracerIfAbsent(Tracer tracer)
        {
            var registeredSuccessfully = GlobalTracer.RegisterIfAbsent(WrapTracer(tracer));

            if (!registeredSuccessfully)
            {
                Log.Warning("An OpenTracing tracer was already registered.");
            }

            return(registeredSuccessfully);
        }
コード例 #2
0
        public void RegisterIfAbsent_called_multiple_times_does_not_throw_exception()
        {
            Assert.False(GlobalTracer.IsRegistered());

            for (var i = 0; i < 10; i++)
            {
                var tracer = Substitute.For <ITracer>();
                GlobalTracer.RegisterIfAbsent(tracer);

                Assert.True(GlobalTracer.IsRegistered());
            }
        }
コード例 #3
0
        public static IServiceCollection AddJaegerTracer(
            this IServiceCollection services,
            IConfiguration configuration,
            Assembly rootAssembly = null)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            return(services.AddSingleton <ITracer>(
                       serviceProvider =>
            {
                var assembly = rootAssembly ?? Assembly.GetEntryAssembly();
                var serviceName = assembly !.GetName().Name;
                var serviceVersion = assembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>() !
                                     .InformationalVersion;

                var hostingEnvironment = serviceProvider.GetService <IWebHostEnvironment>();
                var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>();

                Configuration.SenderConfiguration.DefaultSenderResolver =
                    new SenderResolver(loggerFactory).RegisterSenderFactory <ThriftSenderFactory>();
                var senderConfig =
                    Configuration.SenderConfiguration.FromIConfiguration(loggerFactory,
                                                                         configuration.GetSection("Jaeger"));

                var tracer = new Tracer.Builder(serviceName)
                             .WithTag("service.version", serviceVersion)
                             .WithTag("service.environment_name", hostingEnvironment?.EnvironmentName ?? "unknown")
                             .WithLoggerFactory(loggerFactory)
                             .WithExpandExceptionLogs()
                             .WithReporter(
                    new RemoteReporter.Builder()
                    .WithLoggerFactory(loggerFactory)
                    .WithSender(senderConfig.GetSender())
                    .Build()
                    )
                             .WithSampler(new ConstSampler(true))
                             .Build();

                GlobalTracer.RegisterIfAbsent(tracer);

                return tracer;
            }));
        }
コード例 #4
0
        public static IServiceCollection AddJaeger(this IServiceCollection services)
        {
            if (_initialized)
            {
                return(services);
            }

            _initialized = true;

            var options = GetJaegerOptions(services);

            if (!options.Enabled)
            {
                var defaultTracer = new Tracer.Builder(Assembly.GetEntryAssembly().FullName)
                                    .WithReporter(new NoopReporter())
                                    .WithSampler(new ConstSampler(false))
                                    .Build();

                services.AddSingleton <ITracer>(defaultTracer);

                return(services);
            }

            services.AddSingleton <ITracer>(sp =>
            {
                var loggerFactory = sp.GetRequiredService <ILoggerFactory>();

                var reporter = new RemoteReporter.Builder()
                               .WithSender(new UdpSender(options.UdpHost, options.UdpPort, options.MaxPacketSize))
                               .WithLoggerFactory(loggerFactory)
                               .Build();

                var sampler = GetSampler(options);

                var tracer = new Tracer.Builder(options.ServiceName)
                             .WithReporter(reporter)
                             .WithSampler(sampler)
                             .Build();

                _ = GlobalTracer.RegisterIfAbsent(tracer);

                return(tracer);
            });

            services.AddOpenTracing();

            return(services);
        }
        public static IServiceCollection AddJaeger(this IServiceCollection services, IConfiguration configuration)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.AddSingleton <ITracer>(serviceProvider =>
            {
                var serviceName = Assembly.GetEntryAssembly().GetName().Name;

                var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>();

                Configuration.SenderConfiguration.DefaultSenderResolver = new SenderResolver(loggerFactory).RegisterSenderFactory <ThriftSenderFactory>();

                var senderConfig = Configuration.SenderConfiguration.FromIConfiguration(loggerFactory, configuration.GetSection("Jaeger"));

                var reporter = new RemoteReporter.Builder()
                               .WithLoggerFactory(loggerFactory)
                               .WithSender(senderConfig.GetSender())
                               .Build();

                var sampler = new ConstSampler(sample: true);

                var tracer = new Tracer.Builder(serviceName)
                             .WithLoggerFactory(loggerFactory)
                             .WithExpandExceptionLogs()
                             .WithReporter(reporter)
                             .WithSampler(sampler)
                             .Build();

                GlobalTracer.RegisterIfAbsent(tracer);

                return(tracer);
            });

            // Prevent endless loops when OpenTracing is tracking HTTP requests to Jaeger.
            services.Configure <HttpHandlerDiagnosticOptions>(options => options.IgnorePatterns.Add(request => request.RequestUri.AbsolutePath.EndsWith(JaegerTraceUri)));
            services.Configure <AspNetCoreDiagnosticOptions>(options =>
            {
                options.Hosting.IgnorePatterns.Add(context => context.Request.Path.Value.EndsWith(ServiceStatusUri, StringComparison.InvariantCultureIgnoreCase));
                options.Hosting.IgnorePatterns.Add(context => context.Request.Path.Value.EndsWith(MetricsUri, StringComparison.InvariantCultureIgnoreCase));
                options.Hosting.IgnorePatterns.Add(context => context.Request.Path.Value.StartsWith(SwaggerUri, StringComparison.InvariantCultureIgnoreCase));
            });

            return(services);
        }
コード例 #6
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllers();
     services
     .AddSingleton(serviceProvider =>
     {
         var serviceName = serviceProvider.GetRequiredService <IWebHostEnvironment>().ApplicationName;
         Environment.SetEnvironmentVariable(Jaeger.Configuration.JaegerServiceName, serviceName);
         Environment.SetEnvironmentVariable(Jaeger.Configuration.JaegerSamplerType, ConstSampler.Type);
         var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>();
         var config        = Jaeger.Configuration.FromEnv(loggerFactory);
         var tracer        = config.GetTracer();
         GlobalTracer.RegisterIfAbsent(tracer);
         return(tracer);
     })
     .AddOpenTracing();
 }
コード例 #7
0
    /// <summary>
    /// Initialize the OpenTelemetry SDK with a pre-defined set of exporters, shims, and
    /// instrumentations.
    /// </summary>
    public static void Initialize()
    {
        if (Interlocked.Exchange(ref _firstInitialization, value: 0) != 1)
        {
            // Initialize() was already called before
            return;
        }

        try
        {
            if (TracerSettings.LoadTracerAtStartup || MeterSettings.LoadMetricsAtStartup)
            {
                // Initialize SdkSelfDiagnosticsEventListener to create an EventListener for the OpenTelemetry SDK
                _sdkEventListener = new(EventLevel.Warning);

                // Register to shutdown events
                AppDomain.CurrentDomain.ProcessExit  += OnExit;
                AppDomain.CurrentDomain.DomainUnload += OnExit;

                if (TracerSettings.FlushOnUnhandledException || MeterSettings.FlushOnUnhandledException)
                {
                    AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
                }
            }

            if (TracerSettings.LoadTracerAtStartup)
            {
                var builder = Sdk
                              .CreateTracerProviderBuilder()
                              .SetResourceBuilder(_resourceBuilder)
                              .UseEnvironmentVariables(TracerSettings)
                              .SetSampler(new AlwaysOnSampler())
                              .InvokePlugins(TracerSettings.TracerPlugins);

                _tracerProvider = builder.Build();
                Logger.Information("OpenTelemetry tracer initialized.");
            }

            if (MeterSettings.LoadMetricsAtStartup)
            {
                var builder = Sdk
                              .CreateMeterProviderBuilder()
                              .SetResourceBuilder(_resourceBuilder)
                              .UseEnvironmentVariables(MeterSettings)
                              .InvokePlugins(MeterSettings.MetricPlugins);

                _meterProvider = builder.Build();
                Logger.Information("OpenTelemetry meter initialized.");
            }
        }
        catch (Exception ex)
        {
            Logger.Error(ex, "OpenTelemetry SDK load exception.");
            throw;
        }

        try
        {
            if (_tracerProvider is not null)
            {
                // Instantiate the OpenTracing shim. The underlying OpenTelemetry tracer will create
                // spans using the "OpenTelemetry.AutoInstrumentation.OpenTracingShim" source.
                var openTracingShim = new TracerShim(
                    _tracerProvider.GetTracer("OpenTelemetry.AutoInstrumentation.OpenTracingShim"),
                    Propagators.DefaultTextMapPropagator);

                // This registration must occur prior to any reference to the OpenTracing tracer:
                // otherwise the no-op tracer is going to be used by OpenTracing instead.
                GlobalTracer.RegisterIfAbsent(openTracingShim);
                Logger.Information("OpenTracingShim loaded.");
            }
            else
            {
                Logger.Information("OpenTracingShim was not loaded as the provider is not initialized.");
            }
        }
        catch (Exception ex)
        {
            Logger.Error(ex, "OpenTracingShim exception.");
            throw;
        }
    }