更新时间:2026-01-21 GMT+08:00
分享

通过OpenTelemetry .Net接入APM

华为云APM兼容OpenTelemetry协议,支持直接接收通过OpenTelemetry SDK或Agent上报的链路追踪数据。本文将介绍如何通过OpenTelemetry Java .Net实现通过链路数据对接到APM。

限制条件

使用.NET SDK 8及以上版本。

环境准备

  1. 准备插件/工具:.NET SDK 8
  2. 安装,命令如下:
    sudo apt-get update &&  sudo apt-get install -y dotnet-sdk-8.0
  3. 环境验证,命令如下:
    dotnet --version

示例demo

  1. 初始化应用,命令如下:
    dotnet new web
  2. 替换当前目录下的Program.cs文件,内容如下:
    using System.Globalization;
    
    var builder = WebApplication.CreateBuilder(args);
    var app = builder.Build();
    var logger = app.Logger;
    
    int RollDice()
    {
        return Random.Shared.Next(1, 7);
    }
    
    string HandleRollDice(string? player)
    {
        var result = RollDice();
        if (string.IsNullOrEmpty(player))
        {
            logger.LogInformation("Anonymous player is rolling the dice: {result}", result);
        }
        else
        {
            logger.LogInformation("{player} is rolling the dice: {result}", player, result);
        }
        return result.ToString(CultureInfo.InvariantCulture);
    }
    
    app.MapGet("/rolldice/{player?}", HandleRollDice);
    app.Run();
  3. 替换Properties目录下的launchSettings.json文件,内容如下:
    {
      "$schema": "http://json.schemastore.org/launchsettings.json",
      "profiles": {
        "http": {
          "commandName": "Project",
          "dotnetRunMessages": true,
          "launchBrowser": true,
          "applicationUrl": "http://localhost:8080",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        }
      }
    }
  4. 在包含Program.cs 的目录下构建并运行,命令如下:
    dotnet build 
    dotnet run 
    curl  http://localhost:8080/rolldice

无侵入式接入

  1. 安装自动埋点依赖,命令如下:

    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 
    ./otel-dotnet-auto-install.sh

  2. 添加环境变量,命令如下:

    export OTEL_TRACES_EXPORTER=otlp \
      OTEL_EXPORTER_OTLP_PROTOCOL=grpc \
      OTEL_METRICS_EXPORTER=none \
      OTEL_LOGS_EXPORTER=none \
      OTEL_SERVICE_NAME=应用.组件.环境 \
      OTEL_EXPORTER_OTLP_ENDPOINT=接入地址 \
      OTEL_EXPORTER_OTLP_HEADERS="Authentication=鉴权信息 "
    
    . $HOME/.otel-dotnet-auto/instrument.sh

  3. 运行,命令如下:

    dotnet run &
    curl  http://localhost:8080/rolldice

  4. 登录APM控制台
  5. 单击左侧,选择“管理与监管> 应用性能管理 APM”,进入APM服务页面。
  6. 在左侧导航栏选择“链路追踪 > 指标”。
  7. 在界面左侧树单击环境,单击“接口调用”,切换至接口调用页签,在接口调用页签可以查看接口调用的数据。

  8. 在左侧导航栏选择“链路追踪 > 调用链”,查看调用链信息。

相关文档