4

我正在尝试将 opentelemetry 添加到我的 .net core 5.0 worker 服务项目之一,一切正常,但跟踪没有开始发送到 Jaeger UI,我还注意到 ActivitySource.StartActivity 返回 null,我在谷歌上搜索,看起来像我可能缺少 ActivirtListner 但不确定如何添加到我的工作人员服务中,

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
            services.AddHostedService<Worker>();
            services.AddOpenTelemetryTracing(builder =>
            {
                //IConfiguration config = sp.GetRequiredService<IConfiguration>();
                builder
                    //.SetSampler(new AlwaysOnSampler())
                    .AddHttpClientInstrumentation()
                    //.AddSqlClientInstrumentation()
                    //.AddNServiceBusInstrumentation()
                    //.AddRabbitMqInstrumentation()
                    .AddSource(nameof(Worker))
                    .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("WorkerServiceForTelemetry"))
                    .AddConsoleExporter()
                    .AddAspNetCoreInstrumentation()
                    //.AddOtlpExporter(options => options.Endpoint = new Uri("http://localhost:4317"))
                    .AddJaegerExporter(opts =>
                    {
                        opts.AgentHost = "Jaeger";
                        opts.AgentPort = 6831;
                        opts.ExportProcessorType = ExportProcessorType.Simple;
                    });
            });
        }

这是我的worker.cs文件

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MessageType;
using PublishToRabbitMq;
using System.Diagnostics;
using OpenTelemetry.Context.Propagation;

namespace WorkerServiceForTelemetry
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;
        private static readonly ActivitySource _activity = new(nameof(Worker));
        private static readonly TextMapPropagator Propagator = Propagators.DefaultTextMapPropagator;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //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();
            //}

            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);             
                DoWork();
                await Task.Delay(10000, stoppingToken);
            }
        }

        public void DoWork()
        {
            //using var listener = new ActivityListener
            //{
            //    ShouldListenTo = _ => true,
            //    Sample = (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.AllData,
            //    ActivityStarted = activity => Console.WriteLine($"{activity.ParentId}:{activity.Id} - Start"),
            //    ActivityStopped = activity => Console.WriteLine($"{activity.ParentId}:{activity.Id} - Stop")
            //};

            //ActivitySource.AddActivityListener(listener);

            //var parentContext = Propagator.Extract(default,
            //        ea.BasicProperties,
            //        ActivityHelper.ExtractTraceContextFromBasicProperties);

            //Baggage.Current = parentContext.Baggage;
            Console.WriteLine("this is WorkerServiceForTelemetry is running");
            Console.WriteLine("Publish Message");
            Publish publish = new Publish();
            var context = Activity.Current?.Context;
            for (var i=0; i<=1; i++)
            {
                using (var activity = _activity.StartActivity("RabbitMq Publish", ActivityKind.Server))
                {
                    PersonName person = new PersonName();
                    person.FirstName = "Zafar" + i;
                    person.LastName = "Jamal" + i;
                    publish.SendMessage(person);
                }
            }
        }
    }
}
4

1 回答 1

0

您的问题中有很多注释代码,这使得分析起来有点困难。但似乎您在创建主机后缺少启动主机,这是跟踪提供程序所必需的:

Host
    .CreateDefaultBuilder(args)
    .ConfigureServices((_, services) =>
    {
        ...
        services.AddOpenTelemetryTracing(builder =>
        {
            ...
            builder.AddSource("example");
            builder.AddConsoleExporter();
        });
    })
    .Build()
    .Start();

您可以使用以下方式做等效的事情Sdk.CreateTracerProviderBuilder()

Sdk
    .CreateTracerProviderBuilder()
    .AddConsoleExporter()
    .AddSource("example")
    .Build();
于 2022-01-31T16:01:00.283 回答