다음을 통해 공유


JavaScript용 Azure Monitor OpenTelemetry

npm 버전

시작하기

패키지 설치

npm install @azure/monitor-opentelemetry

현재 지원되는 환경

경고: 이 SDK는 Node.js 환경에서만 작동합니다. 웹 및 브라우저 시나리오에 Application Insights JavaScript SDK 를 사용합니다.

자세한 내용은 지원 정책 참조하세요.

필수 조건

Azure Monitor OpenTelemetry 클라이언트 사용

중요하다:useAzureMonitor 다른 것을 가져오기 전에 호출해야 합니다. 다른 라이브러리를 먼저 가져오는 경우 원격 분석이 손실될 수 있습니다.

import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";

const options: AzureMonitorOpenTelemetryOptions = {
  azureMonitorExporterOptions: {
    connectionString:
      process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
  },
};
useAzureMonitor(options);
  • 연결 문자열은 환경 변수를 APPLICATIONINSIGHTS_CONNECTION_STRING사용하여 설정할 수 있습니다.

구성 / 설정

import { resourceFromAttributes } from "@opentelemetry/resources";
import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";

const resource = resourceFromAttributes({ testAttribute: "testValue" });
const options: AzureMonitorOpenTelemetryOptions = {
  azureMonitorExporterOptions: {
    // Offline storage
    storageDirectory: "c://azureMonitor",
    // Automatic retries
    disableOfflineStorage: false,
    // Application Insights Connection String
    connectionString:
      process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
  },
  samplingRatio: 1,
  instrumentationOptions: {
    // Instrumentations generating traces
    azureSdk: { enabled: true },
    http: { enabled: true },
    mongoDb: { enabled: true },
    mySql: { enabled: true },
    postgreSql: { enabled: true },
    redis: { enabled: true },
    redis4: { enabled: true },
    // Instrumentations generating logs
    bunyan: { enabled: true },
    winston: { enabled: true },
  },
  enableLiveMetrics: true,
  enableStandardMetrics: true,
  browserSdkLoaderOptions: {
    enabled: false,
    connectionString: "",
  },
  resource: resource,
  logRecordProcessors: [],
  spanProcessors: [],
};
useAzureMonitor(options);
옵션 설명 기본값
azureMonitorExporterOptions Azure Monitor OpenTelemetry 내보내기 구성. 자세한 정보는 여기를 참조하십시오.
samplingRatio 샘플링 비율은 [0,1] 범위의 값을 가져야 하며, 1은 모든 데이터가 샘플링되고 0이면 모든 추적 데이터가 샘플링됨을 의미합니다. 1
instrumentationOptions 계측 라이브러리 구성. 자세한 정보는 여기를 참조하십시오.

{
  http: { enabled: true },
  azureSdk: { enabled: true },
  mongoDb: { enabled: true },
  mySql: { enabled: true },
  postgreSql: { enabled: true },
  redis: { enabled: true },
  redis4: { enabled: true },
  bunyan: { enabled: false }, 
  winston: { enabled: false } 
}
      
browserSdkLoaderOptions 웹 계측 구성을 허용합니다.
        
{ 
  enabled: false, 
  connectionString: "" 
}
        
      
resource opentelemetry 리소스. 자세한 정보는 여기를 참조하십시오.
enableLiveMetrics 라이브 메트릭을 활성화/비활성화합니다. true
enableStandardMetrics 표준 메트릭을 활성화/비활성화합니다. true
logRecordProcessors 전역 로거 공급자에 등록할 로그 레코드 프로세서의 배열입니다.
spanProcessors 전역 추적 프로그램 공급자에 등록할 스팬 프로세서의 배열입니다.
enableTraceBasedSamplingForLogs 추적을 기반으로 로그 샘플링을 사용하도록 설정합니다. false
enablePerformanceCounters 성능 카운터를 사용하도록 설정합니다. true

패키지 설치 폴더의 루트 폴더 applicationinsights.json 아래에 있는 구성 파일@azure/monitor-opentelemetry(예: node_modules/@azure/monitor-opentelemetry. 이러한 구성 값은 모든 AzureMonitorOpenTelemetryClient 인스턴스에 적용됩니다.

{
    "samplingRatio": 0.8,
    "enableStandardMetrics": true,
    "enableLiveMetrics": true,
    "instrumentationOptions":{
        "azureSdk": {
            "enabled": false
        }
    },
    ...
}

환경 변수를 사용하여 APPLICATIONINSIGHTS_CONFIGURATION_FILE 사용자 지정 JSON 파일을 제공할 수 있습니다.

process.env["APPLICATIONINSIGHTS_CONFIGURATION_FILE"] = "path/to/customConfig.json";

계측 라이브러리

다음 OpenTelemetry 계측 라이브러리는 Azure Monitor OpenTelemetry의 일부로 포함되어 있습니다.

메모: Azure SDK, MongoDB, MySQL, PostgreSQL, Redis 및 Redis-4 계측은 분산 추적에 대해 기본적으로 사용하도록 설정됩니다. HTTP/HTTPS 계측도 기본적으로 사용하도록 설정됩니다. 다른 모든 계측은 기본적으로 비활성화되어 있으며 계측 옵션에서 설정 enabled: true 하여 활성화할 수 있습니다.

경고: 계측 라이브러리는 실험적인 OpenTelemetry 사양을 기반으로 합니다. Microsoft의 미리 보기 지원 약속은 다음 라이브러리가 Azure Monitor Application Insights로 데이터를 내보내도록 하는 것이지만 호환성이 손상되는 변경 또는 실험적 매핑으로 인해 일부 데이터 요소가 차단될 수 있습니다.

분산 추적

지표

로그

다른 OpenTelemetry 계측은 여기에서 사용할 수 있으며 AzureMonitorOpenTelemetryClient에서 TracerProvider를 사용하여 추가할 수 있습니다.

import { useAzureMonitor } from "@azure/monitor-opentelemetry";
import { registerInstrumentations } from "@opentelemetry/instrumentation";
import { trace, metrics } from "@opentelemetry/api";
import { ExpressInstrumentation } from "@opentelemetry/instrumentation-express";

useAzureMonitor();
registerInstrumentations({
  tracerProvider: trace.getTracerProvider(),
  meterProvider: metrics.getMeterProvider(),
  instrumentations: [new ExpressInstrumentation()],
});

Application Insights 브라우저 SDK 로더

Application Insights 브라우저 SDK 로더를 사용하면 다음 조건에 해당할 때 웹 SDK를 노드 서버 응답에 삽입할 수 있습니다.

  • 응답의 상태 코드는 200입니다.
  • 응답 방법은 GET입니다.
  • 서버 응답에는 Conent-Type html 헤더가 있습니다.
  • Server resonse에는 및 태그가 모두 포함되어 있습니다.
  • 응답에 현재 /backup web Instrumentation CDN 엔드포인트가 포함되어 있지 않습니다. (현재 및 백업 웹 계측 CDN 엔드포인트는 여기)

브라우저 SDK 로더 사용에 대한 자세한 내용은 여기에서 확인할 수 있습니다.

클라우드 역할 이름 및 클라우드 역할 인스턴스 설정

OpenTelemetry 리소스 속성을 통해 클라우드 역할 이름 및 클라우드 역할 인스턴스를 설정할 수 있습니다.

import { emptyResource } from "@opentelemetry/resources";
import {
  ATTR_SERVICE_NAME,
  SEMRESATTRS_SERVICE_NAMESPACE,
  SEMRESATTRS_SERVICE_INSTANCE_ID,
} from "@opentelemetry/semantic-conventions";
import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";

// ----------------------------------------
// Setting role name and role instance
// ----------------------------------------
const customResource = emptyResource();
customResource.attributes[ATTR_SERVICE_NAME] = "my-helloworld-service";
customResource.attributes[SEMRESATTRS_SERVICE_NAMESPACE] = "my-namespace";
customResource.attributes[SEMRESATTRS_SERVICE_INSTANCE_ID] = "my-instance";

const options: AzureMonitorOpenTelemetryOptions = { resource: customResource };
useAzureMonitor(options);

리소스의 표준 속성에 대한 자세한 내용은 Resource Semantic Conventions를 참조하십시오.

원격 분석 수정

이 섹션에서는 원격 분석을 수정하는 방법에 대해 설명합니다.

범위 특성 추가

범위 특성을 추가하려면 다음 두 가지 방법 중 하나를 사용합니다.

  • 계측 라이브러리에서 제공하는 옵션을 사용합니다.
  • 사용자 지정 범위 프로세서를 추가합니다.

이러한 특성에는 원격 분석에 사용자 지정 속성을 추가하는 것이 포함될 수 있습니다.

팁: 계측 라이브러리에서 제공하는 옵션을 사용할 수 있는 경우 사용하는 이점은 전체 컨텍스트를 사용할 수 있다는 것입니다. 결과적으로 사용자는 더 많은 특성을 추가하거나 필터링하도록 선택할 수 있습니다. 예를 들어 HttpClient 계측 라이브러리의 보강 옵션은 사용자에게 httpRequestMessage 자체에 대한 액세스를 제공합니다. 여기에서 무엇이든 선택하고 특성으로 저장할 수 있습니다.

Trace에 사용자 지정 속성 추가

범위에 추가하는 모든 특성 은 사용자 지정 속성으로 내보내집니다.

사용자 지정 프로세서 사용:

import { SpanProcessor, ReadableSpan } from "@opentelemetry/sdk-trace-base";
import { Span } from "@opentelemetry/api";
import { SEMATTRS_HTTP_CLIENT_IP } from "@opentelemetry/semantic-conventions";
import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";

class SpanEnrichingProcessor implements SpanProcessor {
  async forceFlush(): Promise<void> {
    // Flush code here
  }
  async shutdown(): Promise<void> {
    // shutdown code here
  }
  onStart(_span: Span): void {}
  onEnd(span: ReadableSpan): void {
    span.attributes["CustomDimension1"] = "value1";
    span.attributes["CustomDimension2"] = "value2";
    span.attributes[SEMATTRS_HTTP_CLIENT_IP] = "<IP Address>";
  }
}

// Enable Azure Monitor integration.
const options: AzureMonitorOpenTelemetryOptions = {
  // Add the SpanEnrichingProcessor
  spanProcessors: [new SpanEnrichingProcessor()],
};

useAzureMonitor(options);

추적 및 로그에 작업 이름 추가

사용자 지정 범위 프로세서 및 로그 레코드 프로세서를 사용하여 요청의 작업 이름을 종속성 및 로그에 연결하고 상관 관계를 지정합니다.

import { SpanProcessor, ReadableSpan } from "@opentelemetry/sdk-trace-base";
import { Span, Context, trace } from "@opentelemetry/api";
import { AI_OPERATION_NAME } from "@azure/monitor-opentelemetry-exporter";
import { LogRecordProcessor, SdkLogRecord } from "@opentelemetry/sdk-logs";
import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";

class SpanEnrichingProcessor implements SpanProcessor {
  async forceFlush(): Promise<void> {
    // Flush code here
  }
  async shutdown(): Promise<void> {
    // shutdown code here
  }
  onStart(_span: Span, _context: Context): void {
    const parentSpan = trace.getSpan(_context);
    if (parentSpan && "name" in parentSpan) {
      // If the parent span has a name we can assume it is a ReadableSpan and cast it.
      _span.setAttribute(AI_OPERATION_NAME, (parentSpan as unknown as ReadableSpan).name);
    }
  }
  onEnd(_span: ReadableSpan): void {}
}

class LogRecordEnrichingProcessor implements LogRecordProcessor {
  async forceFlush(): Promise<void> {
    // Flush code here
  }
  async shutdown(): Promise<void> {
    // shutdown code here
  }
  onEmit(_logRecord: SdkLogRecord, _context: Context): void {
    const parentSpan = trace.getSpan(_context);
    if (parentSpan && "name" in parentSpan) {
      // If the parent span has a name we can assume it is a ReadableSpan and cast it.
      _logRecord.setAttribute(AI_OPERATION_NAME, (parentSpan as unknown as ReadableSpan).name);
    }
  }
}

// Enable Azure Monitor integration.
const options: AzureMonitorOpenTelemetryOptions = {
  // Add the SpanEnrichingProcessor
  spanProcessors: [new SpanEnrichingProcessor()],
  logRecordProcessors: [new LogRecordEnrichingProcessor()],
};

useAzureMonitor(options);

원격 분석 필터링

다음과 같은 방법을 사용하여 원격 분석이 응용 프로그램을 벗어나기 전에 필터링할 수 있습니다.

  1. 많은 HTTP 계측 라이브러리에서 제공하는 URL 옵션을 제외합니다.

    다음 예에서는 HTTP/HTTPS 계측 라이브러리를 사용하여 추적에서 특정 URL을 제외하는 방법을 보여 줍니다.

    import { HttpInstrumentationConfig } from "@opentelemetry/instrumentation-http";
    import { IncomingMessage, RequestOptions } from "node:http";
    import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";
    
    const httpInstrumentationConfig: HttpInstrumentationConfig = {
      enabled: true,
      ignoreIncomingRequestHook: (request: IncomingMessage) => {
        // Ignore OPTIONS incoming requests
        if (request.method === "OPTIONS") {
          return true;
        }
        return false;
      },
      ignoreOutgoingRequestHook: (options: RequestOptions) => {
        // Ignore outgoing requests with /test path
        if (options.path === "/test") {
          return true;
        }
        return false;
      },
    };
    
    const options: AzureMonitorOpenTelemetryOptions = {
      instrumentationOptions: {
        http: httpInstrumentationConfig,
      },
    };
    
    useAzureMonitor(options);
    
  2. 사용자 지정 프로세서를 사용합니다. 사용자 지정 범위 프로세서를 사용하여 특정 범위를 내보내지 않도록 제외할 수 있습니다. 범위를 내보내지 않도록 표시하려면 TraceFlagDEFAULT로 설정합니다. 사용자 지정 속성 추가 예제를 사용하되 다음 코드 줄을 바꿉니다.

    import { SpanProcessor, ReadableSpan } from "@opentelemetry/sdk-trace-base";
    import { Span, Context, SpanKind, TraceFlags } from "@opentelemetry/api";
    
    class SpanEnrichingProcessor implements SpanProcessor {
      async forceFlush(): Promise<void> {
        // Force flush code here
      }
      onStart(_span: Span, _parentContext: Context): void {
        // Normal code here
      }
      async shutdown(): Promise<void> {
        // Shutdown code here
      }
      onEnd(span: ReadableSpan): void {
        if (span.kind === SpanKind.INTERNAL) {
          span.spanContext().traceFlags = TraceFlags.NONE;
        }
      }
    }
    

사용자 지정 원격 분석

이 섹션에서는 애플리케이션에서 사용자 지정 원격 분석을 수집하는 방법을 설명합니다.

사용자 지정 메트릭 추가

계측 라이브러리에서 수집하는 것 이상의 메트릭을 수집할 수 있습니다.

OpenTelemetry API는 다양한 메트릭 시나리오를 포괄하는 6개의 메트릭 "계측"을 제공하며, Metrics Explorer에서 메트릭을 시각화할 때 올바른 "집계 유형"을 선택해야 합니다. 이 요구 사항은 OpenTelemetry Metric API를 사용하여 메트릭을 전송하고 계측 라이브러리를 사용할 때 적용됩니다.

다음 표에서는 각 OpenTelemetry 지표 계측기에 권장되는 집계 유형을 보여줍니다.

OpenTelemetry 계측기 Azure Monitor 집계 형식
카운터 합계
비동기 카운터 합계
히스토그램 Average, Sum, Count (Python의 경우 Max, Min 및 Node.js에만 해당)
비동기 계기 평균
UpDownCounter (Python 및 Node.js 전용) 합계
비동기 UpDownCounter (Python 및 Node.js 전용) 합계

주의: 테이블에 표시된 것을 벗어난 집계 유형은 일반적으로 의미가 없습니다.

OpenTelemetry 사양은 계측을 설명하고 각 계측을 사용할 수 있는 경우의 예를 제공합니다.

import { useAzureMonitor } from "@azure/monitor-opentelemetry";
import { metrics, ObservableResult } from "@opentelemetry/api";

useAzureMonitor();
const meter = metrics.getMeter("testMeter");

const histogram = meter.createHistogram("histogram");
const counter = meter.createCounter("counter");
const gauge = meter.createObservableGauge("gauge");
gauge.addCallback((observableResult: ObservableResult) => {
  const randomNumber = Math.floor(Math.random() * 100);
  observableResult.observe(randomNumber, { testKey: "testValue" });
});

histogram.record(1, { testKey: "testValue" });
histogram.record(30, { testKey: "testValue2" });
histogram.record(100, { testKey2: "testValue" });

counter.add(1, { testKey: "testValue" });
counter.add(5, { testKey2: "testValue" });
counter.add(3, { testKey: "testValue2" });

사용자 지정 예외 추가

계측 라이브러리를 선택하면 Application Insights에 대한 예외를 자동으로 지원합니다. 그러나 계측 라이브러리가 보고하는 것 이상의 예외를 수동으로 보고해야 할 수도 있습니다. 예를 들어 코드에서 catch된 예외는 일반적으로 보고되지 않으며 , 이를 보고하여 오류 블레이드 및 종단 간 트랜잭션 보기를 포함한 관련 환경에서 주의를 끌 수 있습니다.

import { useAzureMonitor } from "@azure/monitor-opentelemetry";
import { trace, Exception } from "@opentelemetry/api";

useAzureMonitor();
const tracer = trace.getTracer("testMeter");

const span = tracer.startSpan("hello");
try {
  throw new Error("Test Error");
} catch (error) {
  span.recordException(error as Exception);
}

문제 해결

자체 진단

Azure Monitor OpenTelemetry는 내부 로그에 OpenTelemetry API 로거를 사용합니다. 활성화하려면 다음 코드를 사용합니다.

import { useAzureMonitor } from "@azure/monitor-opentelemetry";

process.env["APPLICATIONINSIGHTS_INSTRUMENTATION_LOGGING_LEVEL"] = "VERBOSE";
process.env["APPLICATIONINSIGHTS_LOG_DESTINATION"] = "file";
process.env["APPLICATIONINSIGHTS_LOGDIR"] = "path/to/logs";

useAzureMonitor();

APPLICATIONINSIGHTS_INSTRUMENTATION_LOGGING_LEVEL환경 변수를 사용하여 원하는 로그 수준을 설정할 수 있으며 , NONEERRORWARNINFODEBUGVERBOSE지원합니다. ALL

로그는 환경 변수를 사용하여 APPLICATIONINSIGHTS_LOG_DESTINATION 로컬 파일에 넣을 수 있으며, 지원되는 값은 및 filefile+console이며, * nix 및 applicationinsights.log Windows의 경우 모든 로그를 /tmp 포함하여 기본적으로 tmp 폴더에 명명 USERDIR/AppData/Local/Temp 된 파일이 생성됩니다. 로그 디렉토리는 환경 변수를 사용하여 APPLICATIONINSIGHTS_LOGDIR 구성할 수 있습니다.

예시

몇 가지 챔피언 시나리오의 전체 샘플은 폴더를 참조하십시오 samples/ .

주요 개념

OpenTelemetry 프로젝트에 대한 자세한 내용은 OpenTelemetry 사양을 검토하세요.

플러그인 레지스트리

사용 중인 라이브러리에 대한 플러그인이 이미 만들어졌는지 확인하려면 OpenTelemetry Registry를 확인하십시오.

레지스트리에서 라이브러리를 사용할 수 없는 경우 에서 opentelemetry-js-contrib새 플러그인 요청을 제안해 주십시오.

기여하기

이 라이브러리에 기여하려면 기여 가이드 읽어 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.