

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 遷移至 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>

若要使用適用於 Node.js 的 X-Ray 開發套件追蹤請求，您必須修改應用程式碼。使用 OpenTelemetry，您可以使用零碼自動檢測解決方案來追蹤請求。

**使用 OpenTelemetry 型自動檢測進行零程式碼自動檢測。**

1. 使用適用於 Node.js 的 AWS Distro for OpenTelemetry (ADOT) 自動檢測 – 如需 Node.js 應用程式的自動檢測，請參閱[使用適用於 OpenTelemetry JavaScript 自動檢測的 AWS Distro 追蹤和指標](https://aws-otel.github.io/docs/getting-started/js-sdk/trace-metric-auto-instr)。

   （選用） 您也可以 AWS 在使用 ADOT JavaScript 自動檢測功能自動檢測應用程式時啟用 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 ]

使用適用於 Node.js 的 X-Ray 開發套件時，需要使用 `aws-xray-sdk`套件來設定 X-Ray 開發套件搭配服務外掛程式或本機取樣規則，然後再使用 開發套件來檢測您的程式碼。

```
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 進行設定。不過，目前可透過適用於 Node.js 的 ADOT Auto-Instrumentation 支援 X-Ray 遠端取樣。

針對下列程式碼範例，您將需要下列相依性：

```
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 Agent/OpenTelemetry Collector 時需要
+ 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 等程式庫的範圍。啟用這些項目會自動建立模組的範圍，例如適用於 JavaScript 的 AWS SDK 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 自動檢測支援：
+ 透過環境變數的 X-Ray 遠端取樣 – `export OTEL_TRACES_SAMPLER=xray`
+ 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 開發套件追蹤 *Express.js* 應用程式收到的傳入 HTTP 請求，`AWSXRay.express.closeSegment()`需要兩個中介軟體`AWSXRay.express.openSegment(<name>)`和 來包裝所有定義的路由，以便追蹤它們。

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

...

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

**重新設定**

若要追蹤`Restify`應用程式收到的傳入 HTTP 請求，透過從 Restify Server 上的 `aws-xray-sdk-restify `模組執行啟用，使用 X-Ray 開發套件的中介軟體：

```
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 組態以啟用快速模組的檢測：

```
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 應用程式，您將需要 [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 檢測提供。使用 安裝下列相依性`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 是否支援在[登錄](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 ]

您可以建立並使用自訂範圍來監控檢測程式庫未擷取的內部活動效能。請注意，只有種類的伺服器會轉換為 X-Ray 區段，所有其他範圍則會轉換為 X-Ray 子區段。如需詳細資訊，請參閱[客群](https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-segments)。

在追蹤設定中設定 OpenTelemetry SDK 以建立跨度之後，您將需要一個 Tracer 執行個體。您可以視需要建立任意數量的 Tracer 執行個體，但整個應用程式通常會有一個 Tracer。

```
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`屬性清單。如需詳細資訊，請參閱[啟用自訂 X-Ray 註釋](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 函數啟用 *Active Tracing* 後，需要 X-Ray SDK，無需額外的組態。Lambda 會建立代表 Lambda 處理常式調用的區段，而且您使用 X-Ray SDK 建立子區段或檢測程式庫，而不需要任何其他組態。

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

您可以使用 AWS 付費的 Lambda 層自動檢測 Lambda。有兩種解決方案：
+ （建議）適用於 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 檢測手動建立 Spans**

雖然 ADOT JavaScript Lambda Layer 為您的 Lambda 函數提供自動檢測，但您可能會發現需要在 Lambda 中執行手動檢測，例如，提供自訂資料或在程式庫檢測未涵蓋的 Lambda 函數本身內檢測程式碼。

若要搭配自動檢測執行手動檢測，您需要新增 `@opentelemetry/api`做為相依性。建議此相依性的版本與 ADOT JavaScript SDK 使用的相同相依性版本相同。您可以使用 OpenTelemetry API 在 Lambda 函數中手動建立跨度。

若要使用 NPM 新增`@opentelemetry/api`相依性：

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

------