すべてのプロダクト
Search
ドキュメントセンター

Cloud Monitor:カスタム拡張機能を使用した OpenTelemetry スパンの作成 (Golang)

最終更新日:Jun 23, 2026

Golang エージェントのカスタム拡張機能を使用すると、元のコードを変更することなくカスタム関数を挿入できます。リクエストパラメーターとリクエストボディに基づいて OpenTelemetry スパンを作成し、問題を診断できます。

前提条件

操作手順

  1. 現在のプロジェクトディレクトリの外に hook フォルダーを作成します。go mod init hook コマンドを実行してフォルダーを初期化します。次に、hook フォルダー内に hook.go ファイルを作成し、次のコードを追加します。

    次のコードで、挿入するカスタム拡張機能を定義します。

    package hook
    
    import (
    	"context"
    	"encoding/json"
    	"fmt"
      	"go.opentelemetry.io/otel"
    	"go.opentelemetry.io/otel/attribute"
    	"github.com/alibaba/opentelemetry-go-auto-instrumentation/pkg/api"
    	"net/http"
    )
    
    // 注:挿入されるコードの最初のパラメーターは api.CallContext である必要があります。それ以降のパラメーターは、対象関数のパラメーターと一致する必要があります。
    func httpClientEnterHook(call api.CallContext, t *http.Transport, req *http.Request) {
    	header, _ := json.Marshal(req.Header)
    	fmt.Println("request header is ", string(header))
        tracer := otel.GetTracerProvider().Tracer("")
      	_, span := tracer.Start(context.Background(), "Client/User defined span")
      	span.SetAttributes(attribute.String("client", "client-with-ot"))
      	span.SetAttributes(attribute.Bool("user.defined", true))
      	span.End()
    }
    // 注:挿入されるコードの最初のパラメーターは api.CallContext である必要があります。それ以降のパラメーターは、対象関数の戻り値と一致する必要があります。
    func httpClientExitHook(call api.CallContext, res *http.Response, err error) {
    	header, _ := json.Marshal(res.Header)
    	fmt.Println("response header is ", string(header))
    }
    

    次のコードスニペットでスパンを作成します。

    tracer := otel.GetTracerProvider().Tracer("")
      	_, span := tracer.Start(context.Background(), "Client/User defined span")
      	span.SetAttributes(attribute.String("client", "client-with-ot"))
      	span.SetAttributes(attribute.Bool("user.defined", true))
      	span.End()
  2. テストデモを作成します。

    hook フォルダーとは別のディレクトリに demo アプリケーションフォルダーを作成します。go mod init demo コマンドを実行してフォルダーを初期化します。次に、demo フォルダー内に main.go ファイルを作成し、次のコードを追加します。

    説明

    プロジェクトに OpenTelemetry への依存関係がすでにある場合は、main.go ファイルに _ "go.opentelemetry.io/otel" を追加する必要はありません。それ以外の場合は、この行を追加する必要があります。

    package main
    
    import (
    	"context"
    	"fmt"
    	"io/ioutil"
    	"log"
    	"net/http"
        _ "go.opentelemetry.io/otel"
    )
    
    func main() {
    	// リクエスト URL を定義します。
    	req, _ := http.NewRequestWithContext(context.Background(), "GET", "http://www.aliyun.com", nil)
    	req.Header.Set("otelbuild", "true")
    	client := &http.Client{}
    	resp, _ := client.Do(req)
    
    	// 関数終了時にレスポンスボディを必ずクローズします。
    	defer resp.Body.Close()
    }
    
  3. demo フォルダー内に conf.json 設定ファイルを作成し、次の内容を追加します。

    以下の設定により、Golang エージェントはカスタムフックコードを database/sql::(*DB).Query() 関数にインジェクトします。

    [{
      "ImportPath":"net/http",
      "Function":"RoundTrip",
      "OnEnter":"httpClientEnterHook",
      "ReceiverType": "*Transport",
      "OnExit": "httpClientExitHook",
      "Path": "/path/to/hook" # Path をフックコードのローカルパスに変更してください。
    }]
  4. demo ディレクトリに移動し、instgo ツールを使用してプログラムをコンパイルします。

    $ ./instgo set --rule=./conf.json
    $ ./instgo go build 
  5. デモプログラムを起動します。

    ローカルでプログラムを起動するには、環境変数を設定します。また、コンテナ化を使用してデモプログラムをデプロイすることもできます。

    1. 環境変数を設定します。

      export ARMS_ENABLE=true
      export ARMS_APP_NAME=xxx   # アプリケーション名。
      export ARMS_REGION_ID=xxx   # Alibaba Cloud アカウントのリージョン ID。
      export ARMS_LICENSE_KEY=xxx   # 取得したライセンスキー。
    2. デモプログラムを起動します。

      ./demo
  6. ARMS コンソールの[アプリケーションモニタリング] > [アプリケーションリスト] ページで、アプリケーションのモニタリングデータを表示します。

関連ドキュメント

詳細については、「Golang エージェントのカスタム拡張機能の使用」をご参照ください。