tencent cloud

Feedback

Accessing .NET Applications by Using OpenTelemetry-dotnet (Recommended)

Last updated: 2024-11-01 18:21:32
    Note:
    OpenTelemetry is a collection of tools, APIs, and SDKs for monitoring, generating, collecting, and exporting telemetry data (metrics, logs, and traces) to help users analyze the performance and behaviors of the software. For more information about OpenTelemetry, see the OpenTelemetry Official Website.
    The OpenTelemetry community is active, with rapid technological changes, and widely compatible with mainstream programming languages, components, and frameworks, making its link-tracing capability highly popular for cloud-native microservices and container architectures.
    The OpenTelemetry-dotnet solution supports automatic access of common dependency libraries and frameworks of .NET, such as ASPNET, HTTPCLIENT, and MySQLCONNECTOR, to report link information without modifying the code. For other dependency libraries and frameworks that support automatic access, see the list provided by the OpenTelemetry community. This document describes how to access .NET applications by using the OpenTelemetry .NET SDK.

    Prerequisites

    OpenTelemetry .NET supports both automatic and manual access.

    Automatic Access

    Versions supporting automatic access:
    .NET SDK ≥ 6
    .NET Framework does not support automatic access currently.
    For frameworks supporting automatic access, see the OpenTelemetry official documentation.

    Manual Access

    Versions supporting manual access:
    .NET ≥ 5.0
    .NET Core ≥ 2.0
    .NET Framework ≥ 4.6.1
    For frameworks supporting manual access, see the OpenTelemetry official documentation.

    Demo Application

    The example code Program.cs demonstrates how to access WebApplication to a MySQL database by using MySQLConnector. You can create the corresponding MySQL database or purchase one directly.
    1. Initialize the application.
    dotnet new web
    2. Introduce the dependency packages used in the Demo.
    Microsoft.Extensions.Logging.Abstractions is a necessary package for MySqlConnector.
    dotnet add package MySqlConnector;
    dotnet add package Microsoft.Extensions.Logging.Abstractions;
    3. Modify the content of 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"
    }
    }
    }
    }
    4. Write the business code in Program.cs.
    Program.cs demonstrates how to call the WebApplication API to simulate access to a MySQL database by using MySQLConnector.
    using MySqlConnector;
    
    var builder = WebApplication.CreateBuilder(args);
    var app = builder.Build();
    
    app.MapGet("/", () => "Hello World!");
    
    app.MapGet("/todo", () =>
    {
    string connectionString = "server=localhost;port=3306;User Id=root;password=;Database=MyDB";
    
    using (MySqlConnection myConnnect = new MySqlConnection(connectionString))
    {
    try
    {
    myConnnect.Open();
    using (MySqlCommand myCmd = new MySqlCommand("select * from MyTable", myConnnect))
    {
    using (MySqlDataReader reader = myCmd.ExecuteReader())
    {
    List<Int32> results = new List<Int32>();
    while (reader.Read())
    {
    // Assume we only process data IDs in the first column.
    results.Add(reader.GetInt32(0));
    }
    return "ids:" + string.Join(", ", results);
    }
    }
    }
    catch (Exception ex)
    {
    Console.WriteLine($"Database operation error: {ex.Message}");
    return "Database operation error";
    }
    }
    });
    
    app.Run();

    Previous Steps: Get the Access Point and Token

    1. Log in to the TCOP console.
    2. In the left sidebar, select Application Performance Management > Application list, click Access application.
    3. In the right sidebar Data access drawer, click .NET language.
    4. On the Access .NET application page, select the Region and Business System you want to integrate.
    5. Select Access protocol type as OpenTelemetry.
    6. Reporting method Choose your desired reporting method, and obtain your Access Point and Token.
    Note:
    Report over private network: Using this reporting method, your service needs to run in the Tencent Cloud VPC. Through VPC connecting directly, you can avoid the security risks of public network communication and save on reporting traffic overhead.
    Report over public network: If your service is deployed locally or in non-Tencent Cloud VPC, you can report data in this method. However, it involves security risks in public network communication and incurs reporting traffic fees.

    Automatic Access Scheme (Recommended)

    Step 1: Install opentelemetry-dotnet-instrumentation

    1. Download and execute the script for installing OpenTelemetry .NET instrumentation.
    curl -L -O https://github.com/open-telemetry/opentelemetry-dotnet-instrumentation/releases/latest/download/otel-dotnet-auto-install.sh
    
    chmod -x otel-dotnet-auto-install.sh
    
    sh ./otel-dotnet-auto-install.sh
    2. Set the environment variables and execute the OpenTelemetry .NET instrumentation script.
    chmod -x $HOME/.otel-dotnet-auto/instrument.sh
    
    export OTEL_TRACES_EXPORTER=otlp \\
    OTEL_METRICS_EXPORTER=none \\
    OTEL_LOGS_EXPORTER=none \\
    OTEL_SERVICE_NAME=<service-name> \\ # Replace <service-name> with the actual service name.
    OTEL_EXPORTER_OTLP_PROTOCOL=grpc \\
    OTEL_EXPORTER_OTLP_ENDPOINT=<endpoint> \\ # Replace with the access point obtained in Step 1.
    OTEL_RESOURCE_ATTRIBUTES="token=<token>" # Replace with the token obtained in step 1.
    . $HOME/.otel-dotnet-auto/instrument.sh
    Note:
    If you install opentelemetry-dotnet-instrumentation on macOS systems, the coreutils tool is required.
    brew install coreutils

    Step 2: Run the Application

    1. Build and run the application.
    dotnet build
    dotnet run
    2. Visit the following link in the browser:
    http://localhost:8080
    http://localhost:8080/todo
    Each time you visit this page, OpenTelemetry will automatically create a Trace and report the linkage data to APM.

    Access Verification

    After launching the .NET application, access the corresponding interface through port 8080, for example, https://localhost:8080/todo. In case of normal traffic, the connected application will be displayed in APM > Application list. Click on the Application Name/ID to enter the application details page, then select Instance monitoring to view the connected application instance. Due to some delay in processing observable data, if the application or instance is not found in the console after connecting, please wait about 30 seconds.

    Custom Event Tracking (Optional)

    When automatic event tracking does not meet your scenarios, or you need to add business layer event tracking, you can refer to the following content and use opentelemetry-dotnet-instrumentation to add custom event tracking. This document only demonstrates the most basic custom event tracking method. The OpenTelemetry community provides more flexible custom event tracking methods. For specific methods, see the document Custom instrumentation for .NET provided by the OpenTelemetry community.

    Introduce the Dependency Package System.Diagnostics.DiagnosticSource

    dotnet add package System.Diagnostics.DiagnosticSource

    Create an ActivitySource Instance

    private static readonly ActivitySource RegisteredActivity = new ActivitySource("Examples.ManualInstrumentations.Registered");

    Create an Activity

    using (var activity = RegisteredActivity.StartActivity("Main"))
    {
    // Add the Activity Tag.
    activity?.SetTag("key", "3.1415");
    // Add an Event to the Activity.
    activity?.AddEvent(new("something happened"));
    // Write the business code.
    Thread.Sleep(1000);
    }
    

    Register an ActivitySource in OpenTelemetry.AutoInstrumentation

    Set the environment variable OTEL_DOTNET_AUTO_TRACES_ADDITIONAL_SOURCES. ActivitySources not registered in this way will not be reported.
    export OTEL_DOTNET_AUTO_TRACES_ADDITIONAL_SOURCES=Examples.ManualInstrumentations.Registered

    Manual Access Scheme

    If the .NET SDK version is not later than 6 or .NET Framework is used, but the manual access conditions are met, you can choose manual access for reporting. This document only demonstrates the most basic manual event tracking method. The OpenTelemetry community provides more flexible manual event tracking methods. For specific methods, see the document Instrumentation for .NET provided by the OpenTelemetry community.

    Step 1: Install OpenTelemetry Dependencies Required for Manual Access

    1. Install the OpenTelemetry dependencies required for manual access.
    dotnet add package OpenTelemetry
    dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
    dotnet add package OpenTelemetry.Extensions.Hosting
    2. For applications based on ASP.NET Core, the OpenTelemetry.Instrumentation.AspNetCore dependency is also required.
    dotnet add package OpenTelemetry.Instrumentation.AspNetCore

    Step 2: Initialize the OpenTelemetry SDK

    1. Create a tracerProvider and add the following code at the beginning of your program.
    var serviceName = "<service-name>"; // Replace <service-name> with the actual service name.
    using var tracerProvider = Sdk.CreateTracerProviderBuilder()
    .AddSource(serviceName)
    .SetResourceBuilder(
    ResourceBuilder.CreateDefault().AddService(serviceName)
    .AddAttributes(new Dictionary<string, object>
    {
    ["token"] = "<token>", // Replace <token> with the token obtained in the previous step.
    ["host.name"] = "<host>" // Replace <host> with the actual hostname.
    }))
    .AddOtlpExporter(opt =>
    {
    opt.Endpoint = new Uri("<endpoint>"); // Replace <endpoint> with the access point information obtained in the previous step.
    opt.Protocol = OtlpExportProtocol.Grpc;
    })
    .Build();

    Step 3: Modify the Application Code and Use ActivitySource to Create an Activity

    1. Create an ActivitySource for creating an Activity at any place in the application that requires manual access.
    The ActivitySource is equivalent to a Tracer of OpenTelemetry.
    var MyActivitySource = new ActivitySource(serviceName);
    2. After the ActivitySource is created, create an Activity.
    The Activity is equivalent to a Span of OpenTelemetry.
    using var activity = MyActivitySource.StartActivity("SayHello");
    // Add the Activity Tag.
    activity?.SetTag("key", "3.1415");
    // Add an Event to the Activity.
    activity?.AddEvent(new("something happened"));

    Step 4: Run the Program

    Build and run the application.
    dotnet build
    dotnet run

    Access Verification

    Run the .NET application. In case of normal traffic, the connected application will be displayed in APM > Application list. Click on the Application Name/ID to enter the application details page, then select Instance monitoring to view the connected application instance. Due to some delay in processing observable data, if the application or instance is not found in the console after connecting, please wait about 30 seconds.
    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support