在启动时注册OpenTelemeter,并在运行时动态添加更多功能

iqih9akk  于 2022-10-08  发布在  Redis
关注(0)|答案(0)|浏览(205)

Startup类的ConfigureServices方法中,我注册OpenTelemeter如下:

services.AddOpenTelemetryTracing((builder) =>
                    builder
                    .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("MyService"))
                        .AddAspNetCoreInstrumentation()
                        .AddHttpClientInstrumentation()
                        .AddOtlpExporter(otlpOptions =>
                        {
                            otlpOptions.Endpoint = new Uri("http://localhost:4317");
                        }));

我还想添加Redis工具,但我只有在处理请求时才能访问Redis连接字符串,在该请求中,我提取ClientId并从相应的客户端配置中提取该客户端的Redis连接字符串。在Startup类中,在读取ClientInfo时,我添加了用于检测Redis调用的OpenTelemeter跟踪。

services.AddScoped<ClientInfo>(sp =>
            {
                var context = sp.GetService<IHttpContextAccessor>().HttpContext;
                var clientId = context.Request.Headers["ClientId"].ToString();
                var clientInfo = await GetClientInfo(clientId).Result;
                // ClientInfo will contain Redis connection string. I cache this to avoid fetching repeatedly for same client

                // I cache this ClientId in a dictionary and make sure the below registration happens
                // only once per client Id.
                // RedisConnection is of type IConnectionMultiplexer
                var redisConnection = RedisHelper.GetConnection(clientInfo.RedisConnectionString);
                services.AddOpenTelemetryTracing((builder) =>
                    builder
                    .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("MyService"))
                    .AddRedisInstrumentation(redisConnection)
                        .AddOtlpExporter(otlpOptions =>
                        {
                            otlpOptions.Endpoint = new Uri("http://localhost:4317");
                        }));

                return clientInfo;
            });

当我执行代码时,它只为传入的HTTP请求和传出的HTTP请求创建Span。但不是在利用Redis的调用。然而,如果我在第一个调用本身中添加Redis检测,无论我在哪里注册AddAspNetCoreInstrumentation,那么它都工作得很好。

有没有办法可以在启动时添加一些检测工具,并在运行时通过添加更多检测工具在此基础上进行构建?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题