閱讀英文

共用方式為


新增和修改適用於 .NET、Java、Node.js 和 Python 應用程式的 Azure 監視器 OpenTelemetry

本文提供如何使用 Azure 監視器 Application Insights 為應用程式 新增和修改 OpenTelemetry 的指引。

若要深入了解 OpenTelemetry 概念,請參閱 OpenTelemetry 概觀OpenTelemetry 常見問題

自動收集資料

發行版本會藉由統合 OpenTelemetry 檢測程式庫來自動收集資料。

包含的檢測程式庫

下列 OpenTelemetry 檢測設備程式庫包含在 Azure 監視器 Application Insights 發行版本中。 如需詳細資訊,請參閱 Azure SDK for JavaScript

要求

相依性

記錄

您可使用 AzureMonitorOpenTelemetryOptions 來設定檢測:

// Import Azure Monitor OpenTelemetry
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
// Import OpenTelemetry HTTP Instrumentation to get config type
const { HttpInstrumentationConfig } = require("@azure/monitor-opentelemetry");
    // Import HTTP to get type
const { IncomingMessage } = require("http");

// Specific Instrumentation configs could be added
const httpInstrumentationConfig: HttpInstrumentationConfig = {
    ignoreIncomingRequestHook: (request: IncomingMessage) => {
        return false; //Return true if you want to ignore a specific request 
    },
    enabled: true
};
// Instrumentations configuration
const options: AzureMonitorOpenTelemetryOptions = {
instrumentationOptions: {
    http: httpInstrumentationConfig,
    azureSdk: { enabled: true },
    mongoDb: { enabled: true },
    mySql: { enabled: true },
    postgreSql: { enabled: true },
    redis: { enabled: true },
    redis4: { enabled: true },
}
};

// Enable Azure Monitor integration
useAzureMonitor(options);

註腳

  • ¹:支援自動報告未處理/未攔截的例外狀況
  • ²:支援 OpenTelemetry 計量
  • ³:根據預設,只會在 INFO 層級或更高層級收集記錄。 若要變更此層級,請參閱設定選項
  • 根據預設,只有在 INFO 層級或警告層級執行記錄時,才會收集該記錄。

注意

Azure 監視器 OpenTelemetry 發行版本包含自訂對應和邏輯,可自動發出 Application Insights 標準計量

提示

全部 OpenTelemetry 計量,無論是從檢測程式庫自動收集,還是從自訂程式碼中手動收集,目前都會被視為 Application Insights 的「自訂計量」,以供計費之用。 深入了解

新增社群檢測程式庫

您從 OpenTelemetry 社群包含檢測程式庫時,可以自動收集更多資料。

警告

我們不支援或保證社群檢測程式庫的品質。 若要在我們的意見反應社群中建議發行版本、張貼或附議。 請注意,有些是以實驗性 OpenTelemetry 規格為基礎,而且可能會帶來未來的重大變更。

這裡提供其他 OpenTelemetry 檢測設備,且可以在 ApplicationInsightsClient 中使用 TraceHandler 新增:

   // Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
   const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
   const { metrics, trace, ProxyTracerProvider } = require("@opentelemetry/api");

   // Import the OpenTelemetry instrumentation registration function and Express instrumentation
   const { registerInstrumentations } = require( "@opentelemetry/instrumentation");
   const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');

   // Get the OpenTelemetry tracer provider and meter provider
   const tracerProvider = (trace.getTracerProvider() as ProxyTracerProvider).getDelegate();
   const meterProvider = metrics.getMeterProvider();

   // Enable Azure Monitor integration
   useAzureMonitor();
   
   // Register the Express instrumentation
   registerInstrumentations({
     // List of instrumentations to register
     instrumentations: [
       new ExpressInstrumentation(), // Express instrumentation
     ],
   // OpenTelemetry tracer provider
     tracerProvider: tracerProvider,
     // OpenTelemetry meter provider
     meterProvider: meterProvider
   });

收集自訂遙測

本節說明如何從您的應用程式中收集自訂遙測。

視您的語言和訊號類型而定,有不同的方式可以收集自訂遙測,其中包括:

  • OpenTelemetry API
  • 語言特定的記錄/計量程式庫
  • Application Insights 傳統 API

下表代表目前支援的自訂遙測類型:

語言 自訂事件 自訂計量 相依性 例外狀況 頁面檢視 要求 追蹤
ASP.NET Core
   OpenTelemetry API Yes .是 .是 Yes
   ILogger API Yes
   AI 傳統 API
Java
   OpenTelemetry API Yes .是 .是 Yes
   Logback、Log4j、JUL Yes Yes
   Micrometer Metrics Yes
   AI 傳統 API Yes .是 .是 .是 .是 .是 Yes
Node.js
   OpenTelemetry API Yes .是 .是 Yes
Python
   OpenTelemetry API Yes .是 .是 Yes
   Python 記錄模組 Yes
   事件延伸模組 Yes

注意

Application Insights Java 3.x 會接聽傳送至 Application Insights 傳統 API 的遙測。 同樣地,Application Insights Node.js 3.x 會收集使用 Application Insights 傳統 API 建立的事件。 因此,升級更容易,而且自訂遙測支援的不足之處得以補強,直到全部自訂遙測類型都透過 OpenTelemetry API 支援為止。

新增自訂計量

在此內容中,自定義計量詞彙是指手動檢測您的程序代碼,以收集 OpenTelemetry Instrumentation 連結庫自動收集的其他計量。

OpenTelemetry API 提供六個計量「檢測」來涵蓋各種的計量案例,而且您必須在「計量瀏覽器」中視覺化計量時挑選正確的「彙總類型」。 使用 OpenTelemetry 計量 API 來傳送計量,以及使用檢測程式庫時,這項需求是必要的。

下表顯示每個 OpenTelemetry 計量檢測的建議彙總類型

OpenTelemetry 檢測 Azure 監視器彙總類型
計數器 Sum
非同步計數器 Sum
長條圖 Min、Max、Average、Sum 和 Count
非同步量測計 平均
UpDownCounter Sum
非同步 UpDownCounter Sum

警告

超出表格中所顯示內容的彙總類型通常沒有意義。

OpenTelemetry 規格說明檢測,並提供您何時可以使用每個檢測的範例。

提示

長條圖是最活用且最接近於 Application Insights GetMetric 傳統 API。 Azure 監視器目前會將長條圖檢測扁平化為五種支援的彙總類型,且對百分位數的支援正在進行中。 雖然其他 OpenTelemetry 檢測較不活用,但對您的應用程式效能的影響較小。

長條圖範例

// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");

// Enable Azure Monitor integration
useAzureMonitor();

// Get the meter for the "testMeter" namespace
const meter =  metrics.getMeter("testMeter");

// Create a histogram metric
let histogram = meter.createHistogram("histogram");

// Record values to the histogram metric with different tags
histogram.record(1, { "testKey": "testValue" });
histogram.record(30, { "testKey": "testValue2" });
histogram.record(100, { "testKey2": "testValue" });

計數器範例

// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");

// Enable Azure Monitor integration
useAzureMonitor();

// Get the meter for the "testMeter" namespace
const meter =  metrics.getMeter("testMeter");

// Create a counter metric
let counter = meter.createCounter("counter");

// Add values to the counter metric with different tags
counter.add(1, { "testKey": "testValue" });
counter.add(5, { "testKey2": "testValue" });
counter.add(3, { "testKey": "testValue2" });

量測計範例

// Import the useAzureMonitor function and the metrics module from the @azure/monitor-opentelemetry and @opentelemetry/api packages, respectively.
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");

// Enable Azure Monitor integration.
useAzureMonitor();

// Get the meter for the "testMeter" meter name.
const meter = metrics.getMeter("testMeter");

// Create an observable gauge metric with the name "gauge".
let gauge = meter.createObservableGauge("gauge");

// Add a callback to the gauge metric. The callback will be invoked periodically to generate a new value for the gauge metric.
gauge.addCallback((observableResult: ObservableResult) => {
    // Generate a random number between 0 and 99.
    let randomNumber = Math.floor(Math.random() * 100);

    // Set the value of the gauge metric to the random number.
    observableResult.observe(randomNumber, {"testKey": "testValue"});
});

新增自訂例外狀況

選取檢測程式庫會自動報告 Application Insights 的例外狀況。 不過,您可能想要手動報告超出檢測程式庫報告範圍的例外狀況。 例如,您的程式碼攔截到的例外狀況通常不會報告。 您可能想要對其進行報告,以便在相關的體驗中吸引注意,包括失敗區段和端對端交易檢視。

Node.js SDK 只會將這些手動記錄的跨範圍例外狀況導出至 Application Insights,當例外狀況記錄在遠端、內部範圍的子系上,或是例外狀況記錄在最上層範圍時。

// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { trace } = require("@opentelemetry/api");

// Enable Azure Monitor integration
useAzureMonitor();

// Get the tracer for the "testTracer" namespace
const tracer = trace.getTracer("testTracer");

// Start a span with the name "hello"
let span = tracer.startSpan("hello");

// Try to throw an error
try {
    throw new Error("Test Error");
}

// Catch the error and record it to the span
catch(error){
    span.recordException(error);
}

新增自訂範圍

您可能會想要在兩個案例中新增自訂範圍。 首先,檢測程式庫尚未收集相依性要求時。 其次,您想要將應用程式流程模型化為端對端交易檢視上的範圍時。

// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { trace } = require("@opentelemetry/api");

// Enable Azure Monitor integration
useAzureMonitor();

// Get the tracer for the "testTracer" namespace
const tracer = trace.getTracer("testTracer");

// Start a span with the name "hello"
let span = tracer.startSpan("hello");

// End the span
span.end();

使用 Application Insights 傳統 API 傳送自訂遙測

建議您盡可能使用 OpenTelemetry API,但在某些情況下,您必須使用 Application Insights 傳統 API。

如果您想要新增自訂事件或存取 Application Insights API,請將 @azure/monitor-opentelemetry 套件取代為 applicationinsights v3 Beta 套件。 這提供相同的方法和介面,而且 @azure/monitor-opentelemetry 的全部範例程式碼適用於 v3 Beta 套件。

您必須使用 applicationinsights v3 Beta 套件,才能使用 Application Insights 傳統 API 傳送自訂遙測。 (https://www.npmjs.com/package/applicationinsights/v/beta

// Import the TelemetryClient class from the Application Insights SDK for JavaScript.
const { TelemetryClient } = require("applicationinsights");

// Create a new TelemetryClient instance.
const telemetryClient = new TelemetryClient();

然後使用 TelemetryClient 傳送自訂遙測:

活動

// Create an event telemetry object.
let eventTelemetry = {
    name: "testEvent"
};

// Send the event telemetry object to Azure Monitor Application Insights.
telemetryClient.trackEvent(eventTelemetry);

記錄

// Create a trace telemetry object.
let traceTelemetry = {
    message: "testMessage",
    severity: "Information"
};

// Send the trace telemetry object to Azure Monitor Application Insights.
telemetryClient.trackTrace(traceTelemetry);

例外狀況

// Try to execute a block of code.
try {
    ...
}

// If an error occurs, catch it and send it to Azure Monitor Application Insights as an exception telemetry item.
catch (error) {
    let exceptionTelemetry = {
    exception: error,
    severity: "Critical"
    };
    telemetryClient.trackException(exceptionTelemetry);
}

修改遙測

本節說明如何修改遙測。

新增範圍屬性

這些屬性可能包括將自訂屬性新增至遙測。 您也可以使用屬性來設定 Application Insights 結構描述中的選用欄位,例如用戶端 IP。

將自訂屬性新增至範圍

您新增至範圍的任何屬性都會匯出為自訂屬性。 這些會在要求、追蹤、相依性或例外狀況資料表中填入 customDimensions 欄位。

// Import the necessary packages.
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { ReadableSpan, Span, SpanProcessor } = require("@opentelemetry/sdk-trace-base");
const { SemanticAttributes } = require("@opentelemetry/semantic-conventions");

// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {
  forceFlush(): Promise<void> {
    return Promise.resolve();
  }

  shutdown(): Promise<void> {
    return Promise.resolve();
  }

  onStart(_span: Span): void {}

  onEnd(span: ReadableSpan) {
    // Add custom dimensions to the span.
    span.attributes["CustomDimension1"] = "value1";
    span.attributes["CustomDimension2"] = "value2";
  }
}

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

設定使用者 IP

您可以設定範圍的屬性,以填入要求的 client_IP 欄位。 Application Insights 使用 IP 位址來產生使用者位置屬性,然後依預設捨棄

使用自訂屬性範例,但取代下列幾行程式代碼:

...
// Import the SemanticAttributes class from the @opentelemetry/semantic-conventions package.
const { SemanticAttributes } = require("@opentelemetry/semantic-conventions");

// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {

    onEnd(span) {
    // Set the HTTP_CLIENT_IP attribute on the span to the IP address of the client.
    span.attributes[SemanticAttributes.HTTP_CLIENT_IP] = "<IP Address>";
    }
}

設定使用者識別碼或已驗證的使用者識別碼

您可以使用下列指導填入要求的 user_Iduser_AuthenticatedId 欄位。 使用者識別碼是匿名使用者識別碼。 已驗證的使用者識別碼是已知的使用者識別碼。

重要

在您設定已驗證的使用者識別碼之前,請參閱適用的隱私權法律。

使用自訂屬性範例,但取代下列幾行程式代碼:

...
// Import the SemanticAttributes class from the @opentelemetry/semantic-conventions package.
import { SemanticAttributes } from "@opentelemetry/semantic-conventions";

// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {

    onEnd(span: ReadableSpan) {
    // Set the ENDUSER_ID attribute on the span to the ID of the user.
    span.attributes[SemanticAttributes.ENDUSER_ID] = "<User ID>";
    }
}

新增記錄屬性

const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const bunyan = require('bunyan');

// Instrumentations configuration
const options: AzureMonitorOpenTelemetryOptions = {
    instrumentationOptions: {
        // Instrumentations generating logs
        bunyan: { enabled: true },
    }
};

// Enable Azure Monitor integration
useAzureMonitor(options);

var log = bunyan.createLogger({ name: 'testApp' });
log.info({
    "testAttribute1": "testValue1",
    "testAttribute2": "testValue2",
    "testAttribute3": "testValue3"
}, 'testEvent');

取得追蹤識別碼或範圍識別碼

您可以使用下列步驟來取得目前使用中 Span 的 Trace IDSpan ID

取得程式碼中的要求追蹤識別碼和範圍識別碼:

// Import the trace module from the OpenTelemetry API.
const { trace } = require("@opentelemetry/api");

// Get the span ID and trace ID of the active span.
let spanId = trace.getActiveSpan().spanContext().spanId;
let traceId = trace.getActiveSpan().spanContext().traceId;

下一步