共用方式為


適用於 JavaScript 的 Azure Monitor OpenTelemetry

npm 版本

入門指南

安裝套件

npm install @azure/monitor-opentelemetry

目前支援的環境

警告: 此 SDK 僅適用於 Node.js 環境。 將 Application Insights JavaScript SDK 用於 Web 和瀏覽器方案。

如需詳細資訊,請參閱我們的支援原則

先決條件

啟用 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 表示將採樣所有 Tracing 數據。 1
instrumentationOptions 檢測庫配置。 更多資訊請點擊這裡

{
  http: { enabled: true },
  azureSdk: { enabled: false },
  mongoDb: { enabled: false },
  mySql: { enabled: false },
  postgreSql: { enabled: false },
  redis: { enabled: false },
  bunyan: { enabled: false }, 
  winston: { enabled: false } 
}
      
browserSdkLoaderOptions 允許配置 Web Instrumentations。
        
{ 
  enabled: false, 
  connectionString: "" 
}
        
      
resource Opentelemetry 資源。 更多資訊請點擊這裡
enableLiveMetrics 啟用/禁用實時指標。 true
enableStandardMetrics 啟用/禁用標準指標。 true
logRecordProcessors 要註冊到全域記錄器提供程式的記錄處理器陣列。
spanProcessors 要註冊到全域跟蹤器提供程式的span處理器陣列。
enableTraceBasedSamplingForLogs 啟用基於跟蹤的日誌採樣。 false
enablePerformanceCounters 啟用性能計數器。 true

可以使用位於包安裝資料夾根@azure/monitor-opentelemetry資料夾下的設定檔applicationinsights.json設定選項,例如:node_modules/@azure/monitor-opentelemetry。 這些配置值將應用於所有 AzureMonitorOpenTelemetryClient 實例。

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

可以使用 APPLICATIONINSIGHTS_CONFIGURATION_FILE environment variable 提供自定義 JSON 檔。

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

工具儀器庫

以下 OpenTelemetry 檢測庫包含在 Azure Monitor OpenTelemetry 中。

警告: 插樁庫基於實驗性 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 載入程式允許將 Web SDK 注入節點伺服器回應:

  • 回應的狀態碼為 200
  • 回應方法為 GET
  • 伺服器回應具有 Conent-Type html 標頭。
  • Server resonse 同時包含 and 標籤。
  • 回應不應包含目前/備份 Web 檢測 CDN 端點。 (目前和備份 Web 檢測 CDN 端點如這裡所述)

有關瀏覽器 SDK 載入程式使用的更多資訊, 請參閱此處

設定雲端角色名稱和雲端角色執行個體

您可以通過 OpenTelemetry Resource 屬性設置 Cloud Role Name 和 Cloud Role Instance。

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 = Resource.EMPTY;
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);

有關資源的標準屬性的資訊,請參閱 資源語義約定

修改遙測

本節說明如何修改遙測。

新增範圍屬性

若要新增範圍屬性,請使用下列兩種方式之一:

  • 使用 工具庫所提供的選項。
  • 新增自訂範圍處理器。

這些屬性可能包括將自訂屬性新增至遙測數據。

提示: 使用插樁庫提供的選項(如果可用)的優點是整個上下文都可用。 因此,使用者可以選取要新增或篩選更多屬性。 例如,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);

將作名稱添加到跟蹤和日誌

使用自定義span處理器和日誌記錄處理器,以便將請求中的作名稱附加到依賴項和日誌並與之關聯。

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, LogRecord } 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: LogRecord, _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. 使用自訂處理器。 您可以使用自訂範圍處理器來排除要匯出的特定範圍。 若要將範圍標示為不匯出,請將 TraceFlag 設定為 DEFAULT。 使用添加 自訂屬性範例,但取代以下代碼列:

    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 提供了六個指標“工具”來涵蓋各種指標場景,在 Metrics Explorer 中可視化指標時,您需要選擇正確的“聚合類型”。 使用 OpenTelemetry 計量 API 來傳送計量,以及使用檢測程式庫時,這項需求是必要的。

下表顯示了每個 OpenTelemetry Metric Instruments 的建議聚合類型]。

OpenTelemetry 檢測 Azure 監視器彙總類型
計數器 總和
非同步計數器 總和
直方圖 平均值、總和、計數(最大值、最小值僅適用於 Python 和 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的異常。 但是,您可能希望手動報告超出插樁庫報告的異常。 例如,您的代碼捕獲的異常通常 不會 報告,您可能希望報告它們,從而在相關體驗(包括故障邊欄選項卡和端到端事務檢視)中引起對它們的注意。

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環境變數可用於設置所需的紀錄級別,支援以下值:NONE、、ERRORVERBOSEALLWARNINFODEBUG和 .

可以使用APPLICATIONINSIGHTS_LOG_DESTINATION環境變數將日誌放入本地檔,支援的值為 filefile+console,默認情況下會在 tmp 資料夾中生成一個名為 applicationinsights.log 的檔,包括 *nix 和 USERDIR/AppData/Local/Temp Windows 的所有日誌/tmp。 日誌目錄可以使用 APPLICATIONINSIGHTS_LOGDIR 環境變數進行配置。

範例

有關一些冠軍場景的完整示例,請參閱資料夾 samples/

重要概念

有關 OpenTelemetry 專案的更多資訊,請查看 OpenTelemetry 規範

外掛程式註冊表

要查看是否已為您正在使用的庫製作外掛程式,請查看 OpenTelemetry 註冊表

如果您在註冊表中找不到您的庫,請隨時在 上 opentelemetry-js-contrib建議新的外掛程式請求。

貢獻

如果您想要參與此連結庫,請閱讀 參與指南,以深入瞭解如何建置和測試程序代碼。