Node.js 및 OpenTelemetry

이 페이지는 OpenTelemetry를 사용하여 Node.js 애플리케이션용 Cloud Trace 데이터를 수집하려는 애플리케이션 개발자를 대상으로 합니다. OpenTelemetry는 trace 및 측정항목 데이터를 수집하는 데 사용할 수 있는 공급업체 중립적인 계측 프레임워크입니다. 코드를 계측하는 방법은 계측 및 관측 가능성을 참조하세요.

이 페이지에서는 다음 단계를 안내합니다.

  • OpenTelemetry 패키지를 설치합니다.
  • Cloud Trace로 스팬을 내보내도록 애플리케이션을 구성합니다.
  • 플랫폼을 구성합니다.

출시 정보는 다음을 참조하세요.

OpenTelemetry 참조 콘텐츠는 다음을 확인하세요.

Node.js용 OpenTelemetry에 대한 최신 세부정보 및 추가 문서와 예시는 OpenTelemetry를 참조하세요.

시작하기 전에

  1. Google Cloud 콘솔의 탐색 패널에서 API 및 서비스를 선택하고 API 및 서비스 사용 설정을 클릭한 다음 Cloud Trace API를 사용 설정합니다.

    Cloud Trace API 설정으로 이동

  2. API 사용 설정됨이 표시되어 있으면 API가 이미 사용 설정된 것입니다. 그렇지 않으면 사용 설정 버튼을 클릭합니다.

클라이언트 설치, 초기화, 사용

OpenTelemetry는 다음과 같은 애플리케이션 계측 방법을 제공합니다.

  • Node.js 애플리케이션의 자동 계측

    이 접근 방식을 사용할 경우 @opentelemetry/sdk-trace-node SDK를 포함하도록 애플리케이션을 구성합니다. 하지만 사용 중인 라이브러리의 코드를 변경할 필요가 없습니다.

  • 수동 추적

    이 방식을 사용하는 경우 사용 중인 라이브러리를 수정하여 trace 정보를 수집합니다.

다음 섹션에서는 각 계측의 사용 사례를 보여줍니다.

자동 계측

@opentelemetry/sdk-trace-node 모듈은 Node.js 애플리케이션에 자동 계측을 제공합니다.

자동 계측은 애플리케이션 내에서 다음을 자동으로 식별합니다.

  • Express와 같은 프레임워크
  • HTTP, HTTPS, gRPC와 같은 일반적인 프로토콜
  • MySQL, MongoDB, Redis, PostgreSQL과 같은 데이터베이스
  • 애플리케이션 내의 다른 라이브러리

자동 계측은 바로 사용할 수 있는 추적 기능을 제공하므로 사용 중인 라이브러리의 코드를 변경할 필요가 없습니다. 계측 코드는 자동으로 다음 작업을 수행합니다.

  • 분산 추적을 허용할 수 있도록 인바운드 요청에서 trace 컨텍스트 식별자를 추출합니다(해당하는 경우).
  • 트랜잭션이 애플리케이션을 순회하는 동안 현재 trace 컨텍스트가 전파되도록 보장합니다.
  • 아웃바운드 요청에 trace 컨텍스트 식별자를 추가하여 분산된 trace가 다음 홉으로 진행할 수 있도록 합니다(해당하는 경우).
  • 스팬을 만들고 종료합니다.

이 모듈은 플러그인을 사용하여 애플리케이션을 자동으로 계측하며, 애플리케이션은 스팬을 생성하고 몇 줄의 코드로 엔드 투 엔드 추적을 제공합니다.

수동 계측

수동 추적 모듈인 @opentelemetry/sdk-trace-base는 계측 및 스팬 생성을 완벽하게 제어합니다. async_hooks를 로드하지 않으며, 기본적으로 연속 로컬 스토리지 또는 계측 플러그인을 사용하지 않습니다. 수동 추적은 자동 계측 모듈에 비해 성능 오버헤드에 미치는 영향이 적습니다.

다음 안내에서는 Compute Engine 및 Google Kubernetes Engine용 자동 계측 모듈을 사용하는 방법을 보여줍니다.

Compute Engine

다음 패키지를 설치합니다.

npm install --save @opentelemetry/api
npm install --save @opentelemetry/sdk-trace-node
npm install --save @opentelemetry/sdk-trace-base
npm install --save @google-cloud/opentelemetry-cloud-trace-exporter

앱에 다음 코드를 추가하여 내보내기를 초기화하고 등록합니다.

const opentelemetry = require("@opentelemetry/api");
const { NodeTracerProvider } = require("@opentelemetry/sdk-trace-node");
const { BatchSpanProcessor } = require("@opentelemetry/sdk-trace-base");
const {
  TraceExporter,
} = require("@google-cloud/opentelemetry-cloud-trace-exporter");
// Enable OpenTelemetry exporters to export traces to Google Cloud Trace.
// Exporters use Application Default Credentials (ADCs) to authenticate.
// See https://developers.google.com/identity/protocols/application-default-credentials
// for more details.
const provider = new NodeTracerProvider();

// Initialize the exporter. When your application is running on Google Cloud,
// you don't need to provide auth credentials or a project id.
const exporter = new TraceExporter();

// Configure the span processor to batch and send spans to the exporter
provider.addSpanProcessor(new BatchSpanProcessor(exporter));

GKE

Dockerfile에 다음을 추가합니다.

RUN npm install --save @opentelemetry/api
RUN npm install --save @opentelemetry/sdk-trace-node
RUN npm install --save @opentelemetry/sdk-trace-base
RUN npm install --save @google-cloud/opentelemetry-cloud-trace-exporter

앱에 다음 코드를 추가하여 내보내기를 초기화하고 등록합니다.

const opentelemetry = require("@opentelemetry/api");
const { NodeTracerProvider } = require("@opentelemetry/sdk-trace-node");
const { BatchSpanProcessor } = require("@opentelemetry/sdk-trace-base");
const {
  TraceExporter,
} = require("@google-cloud/opentelemetry-cloud-trace-exporter");
// Enable OpenTelemetry exporters to export traces to Google Cloud Trace.
// Exporters use Application Default Credentials (ADCs) to authenticate.
// See https://developers.google.com/identity/protocols/application-default-credentials
// for more details.
const provider = new NodeTracerProvider();

// Initialize the exporter. When your application is running on Google Cloud,
// you don't need to provide auth credentials or a project id.
const exporter = new TraceExporter();

// Configure the span processor to batch and send spans to the exporter
provider.addSpanProcessor(new BatchSpanProcessor(exporter));

Express 프레임워크를 사용하는 샘플 애플리케이션

OpenTelemetry Express 계측을 사용하면 trace 데이터를 자동으로 수집하여 선택한 백엔드로 내보낼 수 있으므로 이를 통해 분산 시스템을 관찰할 수 있습니다.

Express 프레임워크를 사용하는 애플리케이션에 OpenTelemetry를 사용하려면 다음 단계를 완료하세요.

  1. 다음 패키지를 설치합니다.

    npm install --save @opentelemetry/instrumentation-http
    npm install --save @opentelemetry/instrumentation-express
    
  2. 앱에 다음 코드를 추가하면 모든 지원되는 플러그인이 로드됩니다.

    const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node');
    const provider = new NodeTracerProvider();
    

기본적인 예시는 OpenTelemetry Express 예시를 참조하세요.

커스텀 스팬 만들기

커스텀 스팬을 만들어 시스템 생성 trace에 정보를 추가할 수 있습니다.

커스텀 스팬을 만들려면 소스 코드에 다음을 추가합니다.


// Initialize the OpenTelemetry APIs to use the
// NodeTracerProvider bindings
provider.register();
const tracer = opentelemetry.trace.getTracer("basic");

// Create a span.
const span = tracer.startSpan("foo");

// Set attributes to the span.
span.setAttribute("key", "value");

// Annotate our span to capture metadata about our operation
span.addEvent("invoking work");

// simulate some random work.
for (let i = 0; i <= Math.floor(Math.random() * 40000000); i += 1) {}

// Be sure to end the span.
span.end();
  • getTracer는 추적기의 인스턴스를 반환합니다. 여기서 basic은 추적기 또는 계측 라이브러리의 이름입니다. 이는 스팬을 만드는 사용자를 OpenTelemetry에 알려줍니다.

  • foo는 커스텀 스팬의 이름입니다.

  • invoking work는 샘플 이벤트의 이름입니다. 이는 addEvent API를 사용하는 방법을 보여줍니다.

커스텀 스팬을 만드는 기본적인 예시는 OpenTelemetry 예시를 참조하세요.

플랫폼 구성

Google Cloud 및 기타 플랫폼에서 Cloud Trace를 사용할 수 있습니다.

Google Cloud에서 실행

애플리케이션이 Google Cloud에서 실행되는 경우 클라이언트 라이브러리에 서비스 계정 형식으로 사용자 인증 정보를 제공할 필요가 없습니다. 하지만 Google Cloud Platform에 Cloud Trace API 액세스 범위가 사용 설정되어 있는지 확인해야 합니다.

지원되는 Google Cloud 환경 목록은 환경 지원을 참조하세요.

다음 구성에서는 기본 액세스 범위 설정이 Cloud Trace API를 사용 설정합니다.

커스텀 액세스 범위를 사용하는 경우 Cloud Trace API 액세스 범위가 사용 설정되어 있는지 확인해야 합니다.

  • Google Cloud 콘솔을 사용하여 환경의 액세스 범위를 구성하는 방법에 대한 자세한 내용은 Google Cloud 프로젝트 구성을 참조하세요.

  • gcloud 사용자의 경우 --scopes 플래그를 사용하여 액세스 범위를 지정하고 trace.append Cloud Trace API 액세스 범위를 포함합니다. 예를 들어 Cloud Trace API만 사용 설정된 GKE 클러스터를 만들려면 다음을 수행합니다.

    gcloud container clusters create example-cluster-name --scopes=https://www.googleapis.com/auth/trace.append

로컬 및 기타 위치에서 실행

애플리케이션이 Google Cloud 외부에서 실행되는 경우 클라이언트 라이브러리에 사용자 인증 정보를 서비스 계정 형식으로 제공해야 합니다. 서비스 계정에는 Cloud Trace 에이전트 역할이 포함되어야 합니다. 자세한 내용은 서비스 계정 만들기를 참조하세요.

Google Cloud 클라이언트 라이브러리는 애플리케이션 기본 사용자 인증 정보(ADC)를 사용하여 애플리케이션의 사용자 인증 정보를 찾습니다.

세 가지 방법 중 하나로 이러한 사용자 인증 정보를 제공할 수 있습니다.

  • gcloud auth application-default login 실행

  • 운영체제의 기본 경로에 서비스 계정을 배치합니다. 다음은 Windows 및 Linux의 기본 경로를 보여줍니다.

    • Windows: %APPDATA%/gcloud/application_default_credentials.json

    • Linux: $HOME/.config/gcloud/application_default_credentials.json

  • GOOGLE_APPLICATION_CREDENTIALS 환경 변수를 서비스 계정 경로로 설정합니다.

Linux/macOS

    export GOOGLE_APPLICATION_CREDENTIALS=path-to-your-service-accounts-private-key

Windows

    set GOOGLE_APPLICATION_CREDENTIALS=path-to-your-service-accounts-private-key

PowerShell:

    $env:GOOGLE_APPLICATION_CREDENTIALS="path-to-your-service-accounts-private-key"

trace 보기

Google Cloud 콘솔의 탐색 패널에서 Trace를 선택한 후 Trace 탐색기를 선택합니다.

Trace 탐색기로 이동

문제 해결

Cloud Trace 문제 해결에 대한 자세한 내용은 문제 해결 페이지를 참조하세요.