

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# OpenTelemetry Node.js への移行
<a name="migrate-xray-to-opentelemetry-nodejs"></a>

このセクションでは、Node.js アプリケーションを X-Ray SDK から OpenTelemetry に移行する方法について説明します。自動計装および手動計装アプローチの両方について説明し、一般的なユースケースの具体的な例を示します。

X-Ray Node.js SDK を使用すると、Node.js アプリケーションを手動で計装してトレースできます。このセクションでは、X-Ray 計装から OpenTelemetry 計装に移行するためのコード例を示します。

**Topics**
+ [ゼロコード自動計装ソリューション](#zero-code-instrumentation)
+ [手動計装ソリューション](#manual-instrumentation)
+ [受信リクエストのトレース](#tracing-incoming-requests)
+ [AWS SDK JavaScript V3 計測](#aws-sdk-instrumentation)
+ [送信 HTTP 呼び出しの計測](#http-instrumentation)
+ [他のライブラリの計装サポート](#other-libraries)
+ [トレースデータを手動で作成する](#manual-trace-creation)
+ [Lambda 計装](#lambda-instrumentation)

## ゼロコード自動計装ソリューション
<a name="zero-code-instrumentation"></a>

X-Ray SDK for Node.js を使用してリクエストをトレースするには、アプリケーションコードを変更する必要があります。OpenTelemetry では、ゼロコード自動計装ソリューションを使用してリクエストをトレースできます。

**OpenTelemetry ベースの自動計装を使用したゼロコード自動計装**

1. Node.js 用の AWS Distro for OpenTelemetry (ADOT) 自動計測の使用 – Node.js アプリケーションの自動計測については、[AWS 「 Distro for OpenTelemetry JavaScript 自動計測によるトレースとメトリクス](https://aws-otel.github.io/docs/getting-started/js-sdk/trace-metric-auto-instr)」を参照してください。

   (オプション) ADOT JavaScript 自動計測 AWS を使用して でアプリケーションを自動的に計測するときに CloudWatch Application Signals を有効にして、現在のアプリケーションの状態をモニタリングし、ビジネス目標に照らして長期的なアプリケーションパフォーマンスを追跡することもできます。Application Signals は、アプリケーション、サービス、依存関係をアプリケーション中心の統合ビューで表示し、アプリケーションの状態をモニタリングしてトリアージできるようにします。詳細については、「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。

1. OpenTelemetry JavaScript のゼロコード自動計装の使用 – OpenTelemetry JavaScript を使用した自動計装については、「[JavaScript のゼロコード計装](https://opentelemetry.io/docs/zero-code/js/)」を参照してください。

## 手動計装ソリューション
<a name="manual-instrumentation"></a>

------
#### [ Tracing setup with X-Ray SDK ]

X-Ray SDK for Node.js を使用する場合、SDK を使用してコードを計装する前に、X-Ray SDK をサービスプラグインまたはローカルサンプリングルールで設定するために `aws-xray-sdk` パッケージが必要でした。

```
var AWSXRay = require('aws-xray-sdk');

AWSXRay.config([AWSXRay.plugins.EC2Plugin,AWSXRay.plugins.ElasticBeanstalkPlugin]);
AWSXRay.middleware.setSamplingRules(<path to file>);
```

------
#### [ Tracing setup with OpenTelemetry SDK ]

**注記**  
AWS X-Ray リモートサンプリングは現在、OpenTelemetry JS 用に設定することはできません。ただし、X-Ray リモートサンプリングのサポートは、Node.js の ADOT 自動計装を通じて現在も利用できます。

以下のコード例では、次の依存関係が必要です。

```
npm install --save \
  @opentelemetry/api \
  @opentelemetry/sdk-node \
  @opentelemetry/exporter-trace-otlp-proto \
  @opentelemetry/propagator-aws-xray \
  @opentelemetry/resource-detector-aws
```

アプリケーションコードを実行する前に、OpenTelemetry SDK をセットアップして設定する必要があります。これは、[–-require](https://nodejs.org/api/cli.html#-r---require-module) フラグを使用して実行できます。*instrumentation.js* という名前のファイルを作成します。これには、OpenTelemetry 計装の設定とセットアップが含まれます。

以下のコンポーネントを設定することをお勧めします。
+ OTLPTraceExporter – CloudWatch エージェント/OpenTelemetry コレクターへのトレースのエクスポートに必要です。
+ AWSXRayPropagator – X-Ray と統合された AWS サービスにトレースコンテキストを伝達するために必要です
+ Resource Detectors (Amazon EC2 Resource Detector など) – アプリケーションを実行しているホストのメタデータを検出します。

```
/*instrumentation.js*/
// Require dependencies
const { NodeSDK } = require('@opentelemetry/sdk-node');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-proto');
const { AWSXRayPropagator } = require("@opentelemetry/propagator-aws-xray");
const { detectResources } = require('@opentelemetry/resources');
const { awsEc2Detector } = require('@opentelemetry/resource-detector-aws');

const resource = detectResources({
    detectors: [awsEc2Detector],
});
 
const _traceExporter = new OTLPTraceExporter({
    url: 'http://localhost:4318/v1/traces'
});

const sdk = new NodeSDK({
    resource: resource,
    textMapPropagator: new AWSXRayPropagator(),
    traceExporter: _traceExporter
});

sdk.start();
```

その後、次のような OpenTelemetry 設定でアプリケーションを実行できます。

```
node --require ./instrumentation.js app.js
```

OpenTelemetry SDK ライブラリ計測を使用して、 AWS SDK などのライブラリのスパンを自動的に作成できます。これらを有効にすると、 AWS SDK for JavaScript v3 などのモジュールのスパンが自動的に作成されます。OpenTelemetry には、すべてのライブラリ計装を有効にするか、どのライブラリ計装を有効にするかを指定するオプションがあります。

すべての計装を有効にするには、`@opentelemetry/auto-instrumentations-node` パッケージをインストールします。

```
npm install @opentelemetry/auto-instrumentations-node
```

次に、設定を以下のように更新して、すべてのライブラリ計装を有効にします。

```
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');

...

const sdk = new NodeSDK({
    resource: resource,
     instrumentations: [getNodeAutoInstrumentations()],
     textMapPropagator: new AWSXRayPropagator(),
    traceExporter: _traceExporter
});
```

------
#### [ Tracing setup with ADOT auto-instrumentation for Node.js ]

Node.js の ADOT 自動計装を使用すると、Node.js アプリケーションの OpenTelemetry を自動的に設定できます。ADOT Auto-Instrumentation を使用すると、手動でコードを変更して受信リクエストをトレースしたり、 AWS SDK や HTTP クライアントなどのライブラリをトレースしたりする必要はありません。詳細については、[AWS 「 Distro for OpenTelemetry JavaScript Auto-Instrumentation」の「トレースとメトリクス](https://aws-otel.github.io/docs/getting-started/js-sdk/trace-metric-auto-instr)」を参照してください。

Node.js の ADOT 自動計装は以下をサポートします。
+ 環境変数 `export OTEL_TRACES_SAMPLER=xray` を介した X-Ray リモートサンプリング
+ X-Ray トレースコンテキストの伝播 (デフォルトで有効)
+ リソース検出 (Amazon EC2、Amazon ECS、Amazon EKS 環境のリソース検出はデフォルトで有効になっています。)
+ サポートされているすべての OpenTelemetry 計装の自動ライブラリ計装。`OTEL_NODE_ENABLED_INSTRUMENTATIONS` および `OTEL_NODE_DISABLED_INSTRUMENTATIONS` 環境変数を介して選択的に無効化/有効化できます。
+ スパンの手動作成

------

## 受信リクエストのトレース
<a name="tracing-incoming-requests"></a>

------
#### [ With X-Ray SDK ]

**Express.js**

X-Ray SDK では、*Express.js* アプリケーションで受信された HTTP リクエストをトレースする場合、2 つのミドルウェア `AWSXRay.express.openSegment(<name>)` と `AWSXRay.express.closeSegment()` は、定義されたすべてのルートをラップしてトレースする必要がありました。

```
app.use(xrayExpress.openSegment('defaultName'));

...

app.use(xrayExpress.closeSegment());
```

**Restify**

`Restify` アプリケーションで受信した受信 HTTP リクエストをトレースする場合、X-Ray SDK のミドルウェアは、Restify Server の `aws-xray-sdk-restify `モジュールから enable を実行して使用されました。

```
var AWSXRay = require('aws-xray-sdk');
var AWSXRayRestify = require('aws-xray-sdk-restify');

var restify = require('restify');
var server = restify.createServer();
AWSXRayRestify.enable(server, 'MyApp'));
```

------
#### [ With OpenTelemetry SDK ]

**Express.js**

`Express.js` の受信リクエストのトレースサポートは、[OpenTelemetry HTTP 計装](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http)と [OpenTelemetry Express 計装](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-express)によって提供されます。`npm` で次の依存関係をインストールします。

```
npm install --save @opentelemetry/instrumentation-http @opentelemetry/instrumentation-express
```

OpenTelemetry SDK の設定を更新して、Express モジュールの計装を有効にします。

```
const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http');
const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
...

const sdk = new NodeSDK({
  ...
  
  instrumentations: [
    ...
    // Express instrumentation requires HTTP instrumentation
    new HttpInstrumentation(),
    new ExpressInstrumentation(),
  ],
});
```

**Restify**

Restify アプリケーションの場合は、[OpenTelemetry Restify 計装](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-restify)が必要です。次の依存関係をインストールします。

```
npm install --save @opentelemetry/instrumentation-restify
```

OpenTelemetry SDK 設定を更新して、Restify モジュールの計装を有効にします。

```
const { RestifyInstrumentation } = require('@opentelemetry/instrumentation-restify');
...

const sdk = new NodeSDK({
  ...
  
  instrumentations: [
    ...
    new RestifyInstrumentation(),
  ],
});
```

------

## AWS SDK JavaScript V3 計測
<a name="aws-sdk-instrumentation"></a>

------
#### [ With X-Ray SDK ]

 AWS SDK からの送信 AWS リクエストを計測するには、次の例のようにクライアントを計測しました。

```
import { S3, PutObjectCommand } from '@aws-sdk/client-s3';

const s3 = AWSXRay.captureAWSv3Client(new S3({}));

await s3.send(new PutObjectCommand({
  Bucket: bucketName,
  Key: keyName,
  Body: 'Hello!',
}));
```

------
#### [ With OpenTelemetry SDK ]

DynamoDB、Amazon S3 などのダウンストリーム AWS SDK 呼び出しのトレースサポートは、OpenTelemetry AWS SDK 計測によって提供されます。 Amazon S3 `npm` で次の依存関係をインストールします。

```
npm install --save @opentelemetry/instrumentation-aws-sdk
```

SDK 計測を使用して OpenTelemetry AWS SDK 設定を更新します。

```
import { AwsInstrumentation } from '@opentelemetry/instrumentation-aws-sdk';
...

const sdk = new NodeSDK({
  ...

  instrumentations: [
    ...
    new AwsInstrumentation()
  ],
});
```

------

## 送信 HTTP 呼び出しの計測
<a name="http-instrumentation"></a>

------
#### [ With X-Ray SDK ]

X-Ray を使用した送信 HTTP リクエストの計装では、クライアントを計装する必要がありました。次の例を参照してください。

個々の HTTP クライアント

```
var AWSXRay = require('aws-xray-sdk');
var http = AWSXRay.captureHTTPs(require('http'));
```

すべての HTTP クライアント (グローバル)

```
var AWSXRay = require('aws-xray-sdk');
AWSXRay.captureHTTPsGlobal(require('http'));
var http = require('http');
```

------
#### [ With OpenTelemetry SDK ]

Node.js HTTP クライアントのトレースサポートは、OpenTelemetry HTTP 計装によって提供されます。`npm` で次の依存関係をインストールします。

```
npm install --save @opentelemetry/instrumentation-http
```

OpenTelemetry SDK 設定を次のように更新します。

```
const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http');
...

const sdk = new NodeSDK({
  ...
  
  instrumentations: [
    ...
    new HttpInstrumentation(),
  ],
});
```

------

## 他のライブラリの計装サポート
<a name="other-libraries"></a>

OpenTelemetry JavaScript でサポートされているライブラリ計装の全リストは、[サポートされている計装](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/metapackages/auto-instrumentations-node#supported-instrumentations)にあります。

または、OpenTelemetry レジストリを検索して、OpenTelemetry が「[Registry](https://opentelemetry.io/ecosystem/registry/)」でライブラリの計装をサポートしているかどうかを調べることもできます。

## トレースデータを手動で作成する
<a name="manual-trace-creation"></a>

------
#### [ With X-Ray SDK ]

X-Ray を使用して、アプリケーションを追跡するセグメントとその子サブセグメントを手動で作成するには、`aws-xray-sdk` パッケージコードが必要でした。

```
var AWSXRay = require('aws-xray-sdk');

AWSXRay.enableManualMode();

var segment = new AWSXRay.Segment('myApplication');

captureFunc('1', function(subsegment1) {
  captureFunc('2', function(subsegment2) {

  }, subsegment1);
}, segment);

segment.close();
segment.flush();
```

------
#### [ With OpenTelemetry SDK ]

カスタムスパンを作成して使用することで、計装ライブラリでキャプチャされない内部アクティビティのパフォーマンスをモニタリングできます。Server タイプのスパンのみが X-Ray セグメントに変換され、他のすべてのスパンは X-Ray サブセグメントに変換されることに注意してください。詳細については、「[セグメント](https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-segments)」を参照してください。

トレースセットアップで OpenTelemetry SDK を設定してスパンを作成すると、トレーサーインスタンスが必要になります。必要に応じていくつでもトレーサーインスタンスを作成できますが、アプリケーション全体で 1 つのトレーサーを持つことが一般的です。

```
const { trace, SpanKind } = require('@opentelemetry/api');

// Get a tracer instance
const tracer = trace.getTracer('your-tracer-name');

...

  // This span will appear as a segment in X-Ray
  tracer.startActiveSpan('server', { kind: SpanKind.SERVER }, span => {
    // Do work here

    // This span will appear as a subsegment in X-Ray
    tracer.startActiveSpan('operation2', { kind: SpanKind.INTERNAL }, innerSpan => {
      // Do more work here

      innerSpan.end();
    });
    span.end();
  });
```

**OpenTelemetry SDK を使用してトレースに注釈とメタデータを追加する**

カスタムのキーと値のペアをスパンの属性として追加することもできます。デフォルトでは、これらのスパン属性はすべて X-Ray の未加工データのメタデータに変換されることに注意してください。属性がメタデータではなく注釈に変換されるようにするには、その属性のキーを `aws.xray.annotations` 属性のリストに追加します。詳細については、「[Enable The Customized X-Ray Annotations](https://aws-otel.github.io/docs/getting-started/x-ray#enable-the-customized-x-ray-annotations)」を参照してください。

```
  tracer.startActiveSpan('server', { kind: SpanKind.SERVER }, span => {
    span.setAttribute('metadataKey', 'metadataValue');
    span.setAttribute('annotationKey', 'annotationValue');

    // The following ensures that "annotationKey: annotationValue" is an annotation in X-Ray raw data.
    span.setAttribute('aws.xray.annotations', ['annotationKey']);

    // Do work here

    span.end();
  });
```

------

## Lambda 計装
<a name="lambda-instrumentation"></a>

------
#### [ With X-Ray SDK ]

Lambda 関数で*アクティブトレース*を有効にした後、追加設定なしで X-Ray SDK が必要になりました。Lambda は Lambda ハンドラー呼び出しを表すセグメントを作成し、追加の設定なしで X-Ray SDK を使用してサブセグメントまたは計装ライブラリを作成しました。

------
#### [ With OpenTelemetry SDK ]

 AWS 販売された Lambda レイヤーを使用して Lambda を自動的に計測できます。以下の 2 つのソリューションがあります。
+ (推奨) OpenTelemetry 用の AWS Lambda Layer
**注記**  
この Lambda レイヤーでは、デフォルトで CloudWatch Application Signals が有効になっているため、メトリクスとトレースの両方を収集することで、Lambda アプリケーションのパフォーマンスとヘルスのモニタリングが可能になります。トレースのみが必要な場合は、Lambda 環境変数 `OTEL_AWS_APPLICATION_SIGNALS_ENABLED=false` を設定する必要があります。詳細については、「[Lambda でアプリケーションを有効にする](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Signals-Enable-LambdaMain.html)」を参照してください。
+ AWS ADOT JS 用の マネージド Lambda レイヤー。詳細については、「[AWS Distro for OpenTelemetry Lambda Support For JavaScript](https://aws-otel.github.io/docs/getting-started/lambda/lambda-js)」を参照してください。

**Lambda 計装を使用したスパンの手動作成**

ADOT JavaScript Lambda レイヤーは Lambda 関数の自動計装を提供しますが、Lambda で手動計装を実行する必要がある場合もあります。例えば、カスタムデータの提供やライブラリ計装の対象ではない Lambda 関数内のコードの計装などです。

自動計装とともに手動計装を実行するには、`@opentelemetry/api` を依存関係として追加する必要があります。この依存関係のバージョンは、ADOT JavaScript SDK で使用されるのと同じ依存関係のバージョンにすることをお勧めします。OpenTelemetry API を使用して、Lambda 関数にスパンを手動で作成できます。

NPM を使用して `@opentelemetry/api` 依存関係を追加する方法

```
npm install @opentelemetry/api
```

------