AspNetCore.AsyncInitialization icon indicating copy to clipboard operation
AspNetCore.AsyncInitialization copied to clipboard

It looks like tracing is not working for initializer.

Open voroninp opened this issue 9 months ago • 3 comments

I have a simple initializer with defined ActivitySource.

When I call StartActivity I always get null despite source name is registered in WithTracing method:

builder.Services.AddOpenTelemetry()
        .WithTracing(builder =>
        {
            builder
                .AddAspNetCoreInstrumentation()
                .AddEntityFrameworkCoreInstrumentation()
                .AddSource(customSources); // <--- added in the list of `customSources`

In other types (hosted services) tracing works fine.

It looks like the issue is caused by how Otel library works:

public static OpenTelemetryBuilder AddOpenTelemetry(this IServiceCollection services)
{
    Guard.ThrowIfNull(services);

    if (!services.Any((ServiceDescriptor d) => d.ServiceType == typeof(IHostedService) && d.ImplementationType == typeof(TelemetryHostedService)))
    {
        services.Insert(0, ServiceDescriptor.Singleton<IHostedService, TelemetryHostedService>());
    }

    return new(services);
}

And the underlying issue seems to be the fact that host has no AfterInit event.

voroninp avatar Feb 28 '25 13:02 voroninp

Hi @@voroninp

First, are you sure this is the right library? It's only for ASP.NET Core 2.x. If you're using a newer version (which is likely), you should use Extensions.Hosting.AsyncInitialization instead. Not sure it will change anything to your problem.

When I call StartActivity I always get null

Can you clarify? For what do you get null?

It looks like the issue is caused by how Otel library works:

What makes you say that?

How are you calling AsyncInitialization?

thomaslevesque avatar Feb 28 '25 14:02 thomaslevesque

Sorry, created the ticket in wrong repo.

Can you clarify? For what do you get null?

For the activity.:

public async Task InitializeAsync(CancellationToken cancellationToken)
{
    using var activity = Source.StartActivity();
    ...
}    

But it's an expected behavior when source is not listened.

What makes you say that?

Because they initialize things inside TelemetryHostedService, which is started only when host is started. =(

Image

How are you calling AsyncInitialization?

await app.InitAndRunAsync();

voroninp avatar Feb 28 '25 14:02 voroninp

Ah, I see. Yes, initialization occurs before the application starts, so telemetry hasn't started yet. I guess it's an inherent limitation... I didn't even know anything about telemetry when I made this project.

thomaslevesque avatar Feb 28 '25 14:02 thomaslevesque