All Products
Search
Document Center

Managed Service for OpenTelemetry:Use OpenTelemetry to report the trace data of a .NET application

Last Updated:Sep 09, 2024

After you use OpenTelemetry to instrument a .NET application and report the trace data to Managed Service for OpenTelemetry, Managed Service for OpenTelemetry starts to monitor the .NET application. You can view the monitoring data of the application such as application topology, traces, abnormal transactions, slow transactions, and SQL analysis. This topic describes how to use OpenTelemetry to automatically or manually instrument a .NET application and report trace data.

Background Information

OpenTelemetry supports automatic and manual instrumentation for .NET applications.

  • Automatic instrumentation

    • OpenTelemetry supports automatic instrumentation by using the following .NET versions:

      • .NET SDK 6+

      • OpenTelemetry does not support automatic instrumentation by using .NET Framework.

    • For more information about the frameworks based on which OpenTelemetry supports automatic instrumentation, see Available instrumentations in official OpenTelemetry documentation.

  • Manual and semi-automatic instrumentation

    • Supported versions

      • .NET 5.0 and later

      • .NET Core 2.0 and later

      • .NET Framework 4.6.1 and later

    • Supported frameworks

      Supported frameworks and versions

      Framework

      Supported on Windows-only .NET Framework

      Supported on cross-platform .NET

      (.NET Core)

      Supported version

      Instrumented library

      ASPNET

      Yes

      ASP.NET (.NET Framework) MVC and ASP.NET Web API are not supported.

      N/A

      N/A

      ASPNETCORE

      N/A

      Yes

      N/A

      N/A

      Azure

      Yes

      Yes

      Packages with the Azure. prefix that are released after October 1, 2021 are supported.

      Azure SDK

      Elasticsearch

      Yes

      Yes

      • Elasticsearch .NET clients of V8.0.0 up to, but not including, V8.10.0 are supported.

      • V8.10.0 and later are supported by the Elasticsearch Transport framework.

      Elastic.Clients.Elasticsearch

      Elasticsearch Transport

      Yes

      Yes

      V0.4.16 and later

      Elastic.Transport

      Entity Framework Core

      N/A

      Yes

      V6.0.12 and later

      Microsoft.EntityFrameworkCore

      GraphQL

      N/A

      Yes

      V7.5.0 and later

      GraphQL

      gRPC Client

      Yes

      Yes

      V2.52.0 up to, but not including, V3.0.0

      Grpc.Net.Client

      HttpClient

      Yes

      Yes

      *

      System.Net.Http.HttpClient

      System.Net.HttpWebRequest

      Quartz

      V4.7.1 and earlier are not supported.

      Yes

      V3.4.0 and later

      Quartz

      MassTransit

      N/A

      Yes

      V8.0.0 and later

      MassTransit

      MongoDB

      Yes

      Yes

      V2.13.3 up to, but not including, V3.0.0

      MongoDB.Driver.Core

      MySQL Connector

      Yes

      Yes

      V2.0.0 and later

      MySqlConnector

      MySQL Data

      N/A

      Yes

      V8.1.0 and later

      MySql.Data

      Npgsql

      Yes

      Yes

      V6.0.0 and later

      Npgsql

      NServiceBus

      Yes

      Yes

      V8.0.0 and later

      NServiceBus

      SQL Client

      Yes

      Yes

      Microsoft.Data.SqlClient V3 is not supported.

      StackExchange.Redis

      N/A

      Yes

      V2.0.405 up to, but not including, V3.0.0

      StackExchange.Redis

      WCF Client

      Yes

      Yes

      N/A

      N/A

      WCF Service

      Yes

      N/A

      N/A

      N/A

Sample code

Download the sample code from dotnet-demo.

Method 1: Configure automatic instrumentation for an application

Limits

  • OpenTelemetry supports automatic instrumentation only by using OpenTelemetry SDK for .NET 6.0 or later.

  • OpenTelemetry does not support automatic instrumentation by using .NET Framework.

  1. Use ASP.NET Core to create a web application.

    1. Create an application by using the sample code.

      mkdir dotnet-simple-demo
      cd dotnet-simple-demo
      dotnet new web
    2. Add the following code to the Properties/launchSettings.json file:

      {
        "$schema": "http://json.schemastore.org/launchsettings.json",
        "profiles": {
          "http": {
            "commandName": "Project",
            "dotnetRunMessages": true,
            "launchBrowser": true,
            "applicationUrl": "http://localhost:8080",
            "environmentVariables": {
              "ASPNETCORE_ENVIRONMENT": "Development"
            }
          }
        }
      }
    3. Build the application.

      dotnet build
  2. Configure automatic instrumentation for the application.

    1. Download and run the installation script for automatic instrumentation by using OpenTelemetry SDK for .NET.

      curl -L -O https://github.com/open-telemetry/opentelemetry-dotnet-instrumentation/releases/latest/download/otel-dotnet-auto-install.sh
      
      ./otel-dotnet-auto-install.sh
    2. Configure environment variables and run the automatic instrumentation script.

      Replace <serviceName> with your application name. Replace <endpoint> and <token> with the endpoint and token that you obtained in the Prerequisites section of this topic.

      export OTEL_TRACES_EXPORTER=otlp \
        OTEL_METRICS_EXPORTER=none \
        OTEL_LOGS_EXPORTER=none \
        OTEL_SERVICE_NAME=<serviceName> \
        OTEL_EXPORTER_OTLP_PROTOCOL=grpc
        OTEL_EXPORTER_OTLP_ENDPOINT=<endpoint> \
        OTEL_EXPORTER_OTLP_HEADERS="Authentication=<token>"
      . $HOME/.otel-dotnet-auto/instrument.sh
      Note

      For more information about how to configure environment variables for automatic instrumentation by using OpenTelemetry SDK for .NET, see Configuration and settings in official OpenTelemetry documentation.

  3. Run and access the application.

    1. Run the application.

      dotnet run
    2. Run the following command to access the application. The traces that are generated are automatically reported to Managed Service for OpenTelemetry.

      curl localhost:8080/

Method 2: Manually instrument an application

  1. Go to the dotnet-demo/opentelemetry-demo/manual-demo directory and add the following OpenTelemetry dependencies that are required to manually instrument an application:

    dotnet add package OpenTelemetry
    dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
    dotnet add package OpenTelemetry.Exporter.Console # Optional. This dependency is required if you want to export data in the console.
    dotnet add package OpenTelemetry.Extensions.Hosting
  2. In the OpentelemetryExporterDemo.cs file, create an OpenTelemetry TracerProvider, add an HTTP-based OtlpExporter, and then specify the name of the application of which the trace data is reported and the endpoint that is used to report the trace data.

    using System.Diagnostics;
    using OpenTelemetry;
    using OpenTelemetry.Trace;
    using OpenTelemetry.Resources;
    using OpenTelemetry.Exporter;
    
    namespace Demo
    {
        internal static class OpentelemetryExporterDemo
        {
            internal static void Run()
            {
                Console.WriteLine("otlp running");
                // Specify the name of the application of which you want to report the trace data by using OpenTelemetry.
                var serviceName = "otlp-test";
                using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                    .AddSource(serviceName)
                    .SetResourceBuilder(
                    ResourceBuilder.CreateDefault().AddService(serviceName))
                    .AddOtlpExporter(opt =>
                                     {
                                         // Replace the value of the parameter with the endpoint that you obtained in the "Prerequisites" section of this topic.
                                         opt.Endpoint = new Uri("<endpoint>");
                                         // Report trace data over HTTP.
                                         opt.Protocol = OtlpExportProtocol.HttpProtobuf;
                                     })
                    .AddConsoleExporter() // Optional. Export data in the console.
                    .Build();
                for(int i = 0; i<10; i++)
                {
                    var MyActivitySource = new ActivitySource(serviceName);
                    using var activity = MyActivitySource.StartActivity("SayHello");
                    activity?.SetTag("bar", "Hello World");
                }
            }
        }
    }
  3. Modify the Program.cs file to call OpentelemetryExporterDemo in the Main method.

    using System.Diagnostics;
    using System.Net.Http;
    using OpenTelemetry;
    using OpenTelemetry.Resources;
    using OpenTelemetry.Trace;
    
    
    namespace Demo
    {
        public class Otlp
        {
            public static void Main(string[] args)
            {
                OpentelemetryExporterDemo.Run();
            }
        }
    }
  4. Run the following command in the current path:

    dotnet run

Method 3: Combine automatic instrumentation with manual instrumentation

OpenTelemetry can automatically upload trace data for dozens of .NET frameworks. For more information, see Traces instrumentations.

  1. Go to the dotnet-demo/opentelemetry-demo/auto-demo directory and create a web application by using ASP.NET Core.

    Replace <your-project-name> in the code with your application name.

    mkdir <your-project-name>
    cd <your-project-name>
    dotnet new mvc
  2. Download the OpenTelemetry dependencies that are required to monitor the application.

    dotnet add package OpenTelemetry.Exporter.Console # Export the collected data in the console.
    dotnet add package OpenTelemetry.Extensions.Hosting
    dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol # Export data over OpenTelemetry Protocol (OTLP).
  3. Download dependencies for automatic instrumentation.

    Download the dependencies that are used to automatically instrument an application on the ASP.NET Core framework. When the application receives an HTTP request, a span is automatically generated and then reported. To configure automatic instrumentation for applications on other frameworks, download relevant dependencies from Traces instrumentations.

    dotnet add package OpenTelemetry.Instrumentation.AspNetCore
  4. Modify the code in the <your-project-name>/Program.cs file.

    1. Import the required packages at the beginning of the source file.

      using System.Diagnostics;
      using OpenTelemetry.Exporter;
      using OpenTelemetry.Resources;
      using OpenTelemetry.Trace;
    2. Add the DiagnosticsConfig class at the end of the source file.

      Replace <your-service-name> and <your-host-name> in the code with the actual application name and hostname.

      public static class DiagnosticsConfig
      {
          public const string ServiceName = "<your-service-name>";
          public const string HostName = "<your-host-name>";
          public static ActivitySource ActivitySource = new ActivitySource(ServiceName);
      }
    3. Add the code for initializing OpenTelemetry.

      • Report data over HTTP.

        Replace <http_endpoint> in the following code with the endpoint that you obtained in the "Prerequisites" section of this topic:

        // ...
        builder.Services.AddOpenTelemetry()
            .WithTracing(tracerProviderBuilder =>
                tracerProviderBuilder
                    .AddSource(DiagnosticsConfig.ActivitySource.Name)
                    .SetResourceBuilder(OpenTelemetry.Resources.ResourceBuilder.CreateDefault()
                        .AddAttributes(new Dictionary<string, object> {
                            {"service.name", DiagnosticsConfig.ServiceName},
                            {"host.name",DiagnosticsConfig.HostName}
                        }))
                    .AddAspNetCoreInstrumentation()
                    .AddConsoleExporter() // Optional. Export trace data in the console.
                    .AddOtlpExporter(opt =>
                    {
                        // Report data over HTTP.
                        opt.Endpoint = new Uri("<http_endpoint>");
                        opt.Protocol = OtlpExportProtocol.HttpProtobuf;
                    })
             );
        // ...
      • Report data over gRPC.

        Replace <grpc_endpoint> and <token> in the following code with the endpoint and token that you obtained in the "Prerequisites" section of this topic:

        // ...
        builder.Services.AddOpenTelemetry()
            .WithTracing(tracerProviderBuilder =>
                tracerProviderBuilder
                    .AddSource(DiagnosticsConfig.ActivitySource.Name)
                    .SetResourceBuilder(OpenTelemetry.Resources.ResourceBuilder.CreateDefault()
                        .AddAttributes(new Dictionary<string, object> {
                            {"service.name", DiagnosticsConfig.ServiceName},
                            {"host.name",DiagnosticsConfig.HostName}
                        }))
                    .AddAspNetCoreInstrumentation()
                    .AddConsoleExporter() // Optional. Export trace data in the console.
                    .AddOtlpExporter(opt =>
                    {
                        // Report data over gRPC.
                        opt.Endpoint = new Uri("<grpc_endpoint>");
                        opt.Headers = "Authentication=<token>";
                        opt.Protocol = OtlpExportProtocol.Grpc;
                    })
             );
        // ...

    Complete sample code of the Program.cs file

    // Import the required packages.
    using System.Diagnostics;
    using OpenTelemetry.Exporter;
    using OpenTelemetry.Resources;
    using OpenTelemetry.Trace;
    
    var builder = WebApplication.CreateBuilder(args);
    
    
    builder.Services.AddControllersWithViews();
    
    // Initialize OpenTelemetry.
    builder.Services.AddOpenTelemetry()
        .WithTracing(tracerProviderBuilder =>
            tracerProviderBuilder
                .AddSource(DiagnosticsConfig.ActivitySource.Name)
                .SetResourceBuilder(OpenTelemetry.Resources.ResourceBuilder.CreateDefault()
                    .AddAttributes(new Dictionary<string, object> {
                        {"service.name", DiagnosticsConfig.ServiceName},
                        {"host.name",DiagnosticsConfig.HostName}
                    }))
                .AddAspNetCoreInstrumentation()
                .AddConsoleExporter() // Optional. Export trace data in the console.
                .AddOtlpExporter(opt =>
                {
                    // Report data over HTTP.
                    opt.Endpoint = new Uri("<http_endpoint>");
                    opt.Protocol = OtlpExportProtocol.HttpProtobuf;
    
                    // Report data over gRPC.
                    // opt.Endpoint = new Uri("<grpc_endpoint>");
                    // opt.Headers = "Authentication=<token>";
                    // opt.Protocol = OtlpExportProtocol.Grpc;
                })
         );
    
    
    var app = builder.Build();
    
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.Run();
    
    // Create the DiagnosticsConfig class.
    public static class DiagnosticsConfig
    {
        public const string ServiceName = "<your-service-name>"; // The application name.
        public const string HostName = "<your-host-name>"; // The hostname.
        public static ActivitySource ActivitySource = new ActivitySource(ServiceName);
    }
                                
  5. Run the following command on the terminal to run the project:

    dotnet run

    Sample command output:

    Obtain the URL in the returned information. Example: http://localhost:5107.

    Building...
    info: Microsoft.Hosting.Lifetime[14]
          Now listening on: http://localhost:5107
    info: Microsoft.Hosting.Lifetime[0]
          Application started. Press Ctrl+C to shut down.
    info: Microsoft.Hosting.Lifetime[0]
          Hosting environment: Development
    info: Microsoft.Hosting.Lifetime[0]
          Content root path: /path/to/<your-project-name>
  6. Visit http://localhost:5107 in a browser. If the following page is displayed, the trace data has been reported to the Managed Service for OpenTelemetry console.

    返回页面

View the monitoring data

On the Applications page of the Managed Service for OpenTelemetry console, click the name of the application. On the page that appears, view the trace data.