santosh kumar patro
santosh kumar patro

Reputation: 8231

Implementing Distributed Tracing with Azure AppInsights using OpenTelemetry in .NET

I've been working on implementing distributed tracing in my .NET 8 application using OpenTelemetry. I've referred to the article : https://www.milanjovanovic.tech/blog/introduction-to-distributed-tracing-with-opentelemetry-in-dotnet and I've been successful in viewing the metrics and tracing information using the Jaeger UI.

However, I'm looking to extend this concept and use Azure Application Insights instead of Jaeger UI. My goal is to interpret the tracing and metrics information in Azure AppInsights.

Here is the code I've been using to configure OpenTelemetry:

private static void ConfigureOpenTelemetry(WebApplicationBuilder builder, ConfigurationManager config)
{
    var appConfig = builder.Services.BindValidateReturn<DemoCloudServiceOptions>(config);
    builder.Services.AddOpenTelemetry().UseAzureMonitor();
    builder.Services.AddOpenTelemetry(appConfig.AppInsightsConnString);

    builder.Services.AddOpenTelemetry()
    .ConfigureResource(resource => resource.AddService("MyApp"))
    .WithMetrics(metrics =>
    {
        metrics
            .AddAspNetCoreInstrumentation()
            .AddHttpClientInstrumentation();

        metrics.AddMeter("MyApp");

        metrics.AddOtlpExporter();
    })
    .WithTracing(tracing =>
    {
        tracing
            .AddAspNetCoreInstrumentation()
            .AddHttpClientInstrumentation()
            .AddEntityFrameworkCoreInstrumentation();

        tracing.AddOtlpExporter();
    });

    builder.Logging.AddOpenTelemetry(logging => logging.AddOtlpExporter());
}

Can anyone please help me here by providing their guidance.Any help would be greatly appreciated.

Upvotes: 0

Views: 709

Answers (1)

Harshitha
Harshitha

Reputation: 7367

I am able to log Open telemetry to Application Insights.

I have followed this MSDoc to configure Opentelemetry in .NET Core 8 Application.

Use the configuration in appsettings.json file as mentioned here in my SOThread

My .csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <ApplicationInsightsResourceId>/subscriptions/b83c1ed3-c5b6-44fb-b5ba-2b83a074c23f/resourceGroups/****/providers/microsoft.insights/components/SampleAppInsights</ApplicationInsightsResourceId>
    <UserSecretsId>****</UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Azure.Monitor.OpenTelemetry.Exporter" Version="1.2.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
    <PackageReference Include="OpenTelemetry" Version="1.8.1" />
    <PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.8.1" />
    <PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.8.1" />
    <PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.8.1" />
  </ItemGroup>
</Project>

Thanks @Rahul Rai for the clear explanation.

My Program.cs file:

using Azure.Monitor.OpenTelemetry.Exporter;
using OpenTelemetry;
using OpenTelemetry.Logs;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using System.Diagnostics;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
var conn = builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"];

builder.Logging.ClearProviders()
    .AddOpenTelemetry(loggerOptions =>
    {
        loggerOptions
            .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("MyApp"))         
            .AddAzureMonitorLogExporter(options =>
                options.ConnectionString = conn)     
            .AddConsoleExporter();

        loggerOptions.IncludeFormattedMessage = true;
        loggerOptions.IncludeScopes = true;
        loggerOptions.ParseStateValues = true;
    });

builder.Services.AddApplicationInsightsTelemetry(new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions
{
    ConnectionString = builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]
});

var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
 
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();

app.Run();
  • Even the below code worked for me.
 builder.Services.AddOpenTelemetry()
    .WithTracing(builder =>
    {
        builder.AddAspNetCoreInstrumentation();
        builder.AddConsoleExporter();
        builder.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("MyApp"));
        builder.AddAzureMonitorTraceExporter(options =>
           {
               options.ConnectionString = conn;
           });
        builder.AddConsoleExporter();
    });

Local Traces:

Activity.TraceId:            729cc92ac67fe948aaeeaaa250af5431
Activity.SpanId:             2b2e1eb570dbfe44
Activity.TraceFlags:         Recorded
Activity.ActivitySourceName: Microsoft.AspNetCore
Activity.DisplayName:        GET
Activity.Kind:               Server
Activity.StartTime:          2024-05-24T14:51:20.6775264Z
Activity.Duration:           00:00:00.0011907
Activity.Tags:
    server.address: localhost
    server.port: 7285
    http.request.method: GET
    url.scheme: https
    url.path: /_framework/aspnetcore-browser-refresh.js
    network.protocol.version: 2
    user_agent.original: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0
    http.response.status_code: 200

Application Insights Transaction Search: enter image description here

Logs: enter image description here

  • You can see the local telemetry TraceID is shown in ApplicationInsights as Operation ID.

enter image description here

Upvotes: 0

Related Questions