本指南提供在 Azure Monitor Application Insights 中整合和自定義 OpenTelemetry(OTel)工具的說明。
若要深入瞭解 OpenTelemetry 概念,請參閱 OpenTelemetry 概觀 或 OpenTelemetry 常見問題。
自動收集資料
發行版本會藉由統合 OpenTelemetry 檢測程式庫來自動收集資料。
包含的工具程式庫
請求
依賴
Logging
若要減少或增加傳送至 Azure 監視器的記錄數目,請設定記錄以設定適當的記錄層級或套用篩選。 例如,您可以選擇只傳送 Warning 和 Error 記錄至 OpenTelemetry/Azure 監視器。 OpenTelemetry 不會控制記錄路由或篩選 -您的 ILogger 設定會做出這些決策。 如需了解如何設定 ILogger 的詳細資訊,請參閱 設定日誌。
如需有關ILogger的詳細資訊,請參閱C# 和 .NET 中的記錄以及程式代碼範例。
Azure 監視器匯出工具不包含任何檢測程式庫。
您可以使用下列程式代碼範例,從 Azure 軟體開發工具包 (SDK) 收集相依性,以手動訂閱來源。
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
// The following line subscribes to dependencies emitted from Azure SDKs
.AddSource("Azure.*")
.AddAzureMonitorTraceExporter()
.AddHttpClientInstrumentation(o => o.FilterHttpRequestMessage = (_) =>
{
// Azure SDKs create their own client span before calling the service using HttpClient
// In this case, we would see two spans corresponding to the same operation
// 1) created by Azure SDK 2) created by HttpClient
// To prevent this duplication we are filtering the span from HttpClient
// as span from Azure SDK contains all relevant information needed.
var parentActivity = Activity.Current?.Parent;
if (parentActivity != null && parentActivity.Source.Name.Equals("Azure.Core.Http"))
{
return false;
}
return true;
})
.Build();
若要減少或增加傳送至 Azure 監視器的記錄數目,請設定記錄以設定適當的記錄層級或套用篩選。 例如,您可以選擇只傳送 Warning 和 Error 記錄至 OpenTelemetry/Azure 監視器。 OpenTelemetry 不會控制記錄路由或篩選 -您的 ILogger 設定會做出這些決策。 如需了解如何設定 ILogger 的詳細資訊,請參閱 設定日誌。
請求
- Java Message Service (JMS) 取用者
- Kafka 取用者
- Netty
- 石英
- RabbitMQ
- Servlet
- Spring 排程
附註
Servlet 和 Netty 自動檢測涵蓋大部分的 Java HTTP 服務,包括 Java EE、Jakarta EE、Spring Boot、Quarkus 和 Micronaut。
相依性 (加上下游分散式追蹤傳播)
- Apache HttpClient
- Apache HttpAsyncClient
- AsyncHttpClient
- 谷歌 HttpClient
- gRPC
- java.net.HttpURLConnection
- Java 11 Http客戶端
- JAX-RS 用戶端
- Jetty HttpClient (Jetty HTTP客戶端)
- JMS (Java 消息服务)
- Kafka
- Netty 用戶端
- OkHttp
- RabbitMQ
相依性(不含下游分散式追蹤傳播)
- 支援 Cassandra
- 支援 Java 資料庫連線能力 (JDBC)
- 支援 MongoDB (異步和同步處理)
- 支援 Redis (Lettuce 和 Jedis)
指標
- Micrometer 計量,包括 Spring Boot 傳動器計量
- Java 管理延伸模組 (JMX) 計量
日志
- Logback (包括 MDC 屬性) ¹
- Log4j (包括 MDC/線程內容屬性) 2
- JBoss 記錄 (包括 MDC 屬性) ¹
- java.util.logging ¹
若要減少或增加 Azure 監視器所收集的記錄數目,請先在應用程式的記錄連結庫中設定所需的記錄層級(例如 WARNING 或 ERROR)。
默認集合
預設會自動收集下列 Azure SDK 所發出的遙測資料:
[//]: # "Azure Cosmos DB 4.22.0+ due to https://github.com/Azure/azure-sdk-for-java/pull/25571"
[//]: # "the remaining above names and links scraped from https://azure.github.io/azure-sdk/releases/latest/java.html"
[//]: # "and version synched manually against the oldest version in maven central built on azure-core 1.14.0"
[//]: # ""
[//]: # "var table = document.querySelector('#tg-sb-content > div > table')"
[//]: # "var str = ''"
[//]: # "for (var i = 1, row; row = table.rows[i]; i++) {"
[//]: # " var name = row.cells[0].getElementsByTagName('div')[0].textContent.trim()"
[//]: # " var stableRow = row.cells[1]"
[//]: # " var versionBadge = stableRow.querySelector('.badge')"
[//]: # " if (!versionBadge) {"
[//]: # " continue"
[//]: # " }"
[//]: # " var version = versionBadge.textContent.trim()"
[//]: # " var link = stableRow.querySelectorAll('a')[2].href"
[//]: # " str += '* [' + name + '](' + link + ') ' + version + '\n'"
[//]: # "}"
[//]: # "console.log(str)"
Spring Boot 原生應用程式的要求
- Spring Web框架
- Spring Web MVC (模型-View-Controller)
- Spring WebFlux
Spring Boot 原生應用程式的相依性
指標
Spring Boot 原生應用程式的記錄
若要減少或增加 Azure 監視器所收集的記錄數目,請先在應用程式的記錄連結庫中設定所需的記錄層級(例如 WARNING 或 ERROR)。
如需 Quartz 原生應用程式,請參閱 Quarkus 文件。
附註
Quarkus 社群支援並維護 Quarkus 擴充功能。 如需協助,請使用 Quarkus 社群支援管道。 Microsoft 不提供此整合的技術支援。
下列 OpenTelemetry 檢測設備程式庫包含在 Azure 監視器 Application Insights 發行版本中。 如需詳細資訊,請參閱 適用於 JavaScript 的 Azure SDK。
請求
依賴
日志
若要減少或增加 Azure 監視器所收集的記錄數目,請先在應用程式的記錄連結庫中設定所需的記錄層級(例如 WARNING 或 ERROR)。
您可使用 AzureMonitorOpenTelemetryOptions 來設定檢測:
export class BunyanInstrumentationSample {
static async run() {
// Dynamically import Azure Monitor and Bunyan
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const bunyanMod = await import("bunyan");
const bunyan = (bunyanMod as any).default ?? bunyanMod;
// Enable Azure Monitor integration and bunyan instrumentation
const options = {
instrumentationOptions: {
bunyan: { enabled: true },
},
};
const monitor = useAzureMonitor(options);
// Emit a test log entry
const log = (bunyan as any).createLogger({ name: "testApp" });
log.info(
{
testAttribute1: "testValue1",
testAttribute2: "testValue2",
testAttribute3: "testValue3",
},
"testEvent"
);
console.log("Bunyan log emitted");
}
}
請求
依賴
日志
若要減少或增加 Azure 監視器所收集的記錄數目,請先在應用程式的記錄連結庫中設定所需的記錄層級(例如 WARNING 或 ERROR)。
您可以在 GitHub 上找到使用 Python 記錄連結庫的範例。
根據預設,系統會自動 收集 Azure 軟體開發工具套件 (SDK) 發出的遙測。
腳注
- ¹:支援自動報告未處理/未攔截的例外狀況
- ²:支援 OpenTelemetry 計量
秘訣
全部 OpenTelemetry 計量,無論是從檢測程式庫自動收集,還是從自訂程式碼中手動收集,目前都會被視為 Application Insights 的「自訂計量」,以供計費之用。
深入瞭解。
您可以從 OpenTelemetry 社群中納入追蹤程式庫,自動收集更多資料。
警告
我們不支援或保證社群檢測程式庫的品質。 如果要為我們的發行版提出建議,可以在我們的 意見反應社群中發表相關貼文或進行按讚。 請注意,有些是以實驗性 OpenTelemetry 規格為基礎,而且可能會帶來未來的重大變更。
若要新增社群程式庫,請在新增程式庫的 NuGet 套件之後,使用 ConfigureOpenTelemetryMeterProvider 或 ConfigureOpenTelemetryTracerProvider 方法。
下列範例示範如何新增 運行時間檢測 來收集額外的計量:
dotnet add package OpenTelemetry.Instrumentation.Runtime
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add runtime instrumentation.
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddRuntimeInstrumentation());
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
下列範例示範如何新增 運行時間檢測 來收集額外的計量:
// Create a new OpenTelemetry meter provider and add runtime instrumentation and the Azure Monitor metric exporter.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddRuntimeInstrumentation()
.AddAzureMonitorMetricExporter();
您無法使用社群檢測程式庫擴充 Java 發行版本。 若要要求我們包含另一個檢測程式庫,請在 GitHub 頁面上提出問題。 您可以在 後續步驟中找到 GitHub 頁面的連結。
您無法將社群工具程式庫與 GraalVM Java 原生應用程式一起使用。
export class RegisterExpressInstrumentationSample {
static async run() {
// Dynamically import Azure Monitor and Express instrumentation
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { registerInstrumentations } = await import("@opentelemetry/instrumentation");
const { ExpressInstrumentation } = await import("@opentelemetry/instrumentation-express");
// Initialize Azure Monitor (uses env var if set)
const monitor = useAzureMonitor();
// Register the Express instrumentation
registerInstrumentations({
instrumentations: [new ExpressInstrumentation()],
});
console.log("Express instrumentation registered");
}
}
若要新增社群儀器程式庫 (未在 Azure 監視器發行版本中正式支援或包含),您可以直接使用儀器進行操作。 您可以 在這裡找到社群樂器庫的清單。
附註
不建議使用 搭配散發版本 instrument() 手動檢測configure_azure_monitor()。 這不是受支援的情境,您可能會在遙測中遇到不想要的行為。
# Import the `configure_azure_monitor()`, `SQLAlchemyInstrumentor`, `create_engine`, and `text` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
from sqlalchemy import create_engine, text
# Configure OpenTelemetry to use Azure Monitor.
configure_azure_monitor()
# Create a SQLAlchemy engine.
engine = create_engine("sqlite:///:memory:")
# SQLAlchemy instrumentation is not officially supported by this package, however, you can use the OpenTelemetry `instrument()` method manually in conjunction with `configure_azure_monitor()`.
SQLAlchemyInstrumentor().instrument(
engine=engine,
)
# Database calls using the SQLAlchemy library will be automatically captured.
with engine.connect() as conn:
result = conn.execute(text("select 'hello world'"))
print(result.all())
資源偵測器
資源偵測器會在啟動時探索環境中繼資料,並填入 OpenTelemetry 資源屬性 ,例如 service.name、 cloud.provider和 cloud.resource_id。 此中繼資料可支援 Application Insights 中的體驗,例如 Application Map 和計算連結,並改善追蹤、計量和記錄之間的相互關聯。
秘訣
資源屬性描述程序及其環境。 跨度屬性描述單一作業。 將資源屬性用於應用程式層級屬性,例如 service.name。
支援的環境
| 環境 |
偵測的運作方式 |
註釋 |
| Azure App Service |
語言 SDK 或 Azure 監視器發行版本會讀取已知的 App Service 環境變數和主機中繼資料 |
當您使用本文中的指引時,可與 .NET、Java、Node.js和 Python 搭配使用。 |
| Azure Functions |
請參閱 Azure Functions OpenTelemetry 操作說明 |
所有 Azure Functions 的指導性內容都集中在那裡。 |
| Azure 虛擬機器 |
語言 SDK 或發行套件會查詢 Azure 實例中繼資料服務 |
請確定 VM 可以存取執行個體中繼資料服務端點。 |
| Azure Kubernetes Service (AKS) |
使用 OpenTelemetry 收集器 k8sattributes 處理器來新增 Kubernetes 中繼資料 |
建議用於所有執行於 AKS 的語言。 |
| Azure 容器應用程式 |
偵測器會在可用時對環境變數和資源識別碼進行映射。 |
您也可以設定 OTEL_RESOURCE_ATTRIBUTES 以填補間隙。 |
手動和自動儀器
自動化儀器和 Azure 監視器發佈版可在支援的 Azure 環境中執行時啟用資源檢測。
對於手動設定,您可以使用標準 OpenTelemetry 選項直接設定資源屬性:
# Applies to .NET (ASP.NET/ASP.NET Core), Java, Node.js, and Python
export OTEL_SERVICE_NAME="my-service"
export OTEL_RESOURCE_ATTRIBUTES="cloud.provider=azure,cloud.region=westus,cloud.resource_id=/subscriptions/<SUB>/resourceGroups/<RG>/providers/Microsoft.Web/sites/<APP>"
在 Windows PowerShell 上:
$Env:OTEL_SERVICE_NAME="my-service"
$Env:OTEL_RESOURCE_ATTRIBUTES="cloud.provider=azure,cloud.region=westus,cloud.resource_id=/subscriptions/<SUB>/resourceGroups/<RG>/providers/Microsoft.Web/sites/<APP>"
OTLP 擷取考量
- Application Insights 用
service.name 來衍生雲端角色名稱。 為每個服務選擇一個穩定的名稱,以避免應用程式對應中的節點碎片化。
-
cloud.resource_id 改善與 Azure 資源的計算連結。 如果遺漏此屬性,某些體驗可能不會顯示產生資料的 Azure 資源。
收集自訂遙測資料
本節說明如何從您的應用程式中收集自訂遙測。
視您的語言和訊號類型而定,有不同的方式可以收集自訂遙測,其中包括:
- OpenTelemetry 應用程式介面
- 語言特定的記錄/計量程式庫
- Application Insights 經典 API
下表代表目前支援的自訂遙測類型:
| 語言 |
自訂事件 |
自訂計量 |
相依性 |
例外狀況 |
頁面檢視 |
請求事項 |
痕跡 |
|
ASP.NET 核心 |
|
|
|
|
|
|
|
| OpenTelemetry 應用程式介面 |
|
是的 |
是的 |
是的 |
|
是的 |
|
ILogger 應用程式介面 |
|
|
|
|
|
|
是的 |
| AI 傳統 API |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
爪哇島 |
|
|
|
|
|
|
|
| OpenTelemetry 應用程式介面 |
|
是的 |
是的 |
是的 |
|
是的 |
|
Logback、Log4j、JUL |
|
|
|
是的 |
|
|
是的 |
| 微計計量 |
|
是的 |
|
|
|
|
|
| AI 傳統 API |
是的 |
是的 |
是的 |
是的 |
是的 |
是的 |
是的 |
|
|
|
|
|
|
|
|
|
Node.js |
|
|
|
|
|
|
|
| OpenTelemetry 應用程式介面 |
|
是的 |
是的 |
是的 |
|
是的 |
|
|
|
|
|
|
|
|
|
|
Python(編程語言) |
|
|
|
|
|
|
|
| OpenTelemetry 應用程式介面 |
|
是的 |
是的 |
是的 |
|
是的 |
|
| Python 記錄模組 |
|
|
|
|
|
|
是的 |
| 事件延伸模組 |
是的 |
|
|
|
|
|
是的 |
附註
Application Insights Java 3.x 和 Application Insights Node.js 3.x 會從 Application Insights 傳統 API 收集遙測。 此行為可簡化升級,並暫時支援自定義遙測,直到 OpenTelemetry API 包含所有自定義遙測類型為止。
新增自訂計量
在此內容中,自訂計量字詞是指手動檢測您的程式碼,以收集 OpenTelemetry 檢測程式庫自動收集以外的額外計量。 若要深入了解如何使用計量,請參閱 Application Insights 中的計量。
OpenTelemetry API 提供六個度量「工具」來涵蓋各種的度量案例,並在「度量瀏覽器」中視覺化度量時,您需要選擇正確的「彙總類型」。 使用 OpenTelemetry 計量 API 來傳送計量,以及使用檢測程式庫時,這項需求是必要的。
下表顯示每個 OpenTelemetry Metric Instruments 的建議 匯總類型 。
| OpenTelemetry 檢測 |
Azure 監視器彙總類型 |
| 計數器 |
合計 |
| 非同步計數器 |
合計 |
| 長條圖 |
最小值、最大值、平均值、總和和計數 |
| 非同步量測計 |
平均 |
| UpDownCounter |
合計 |
| 非同步 UpDownCounter |
合計 |
OpenTelemetry 規格會描述儀器,並提供何時可以使用每個儀器的範例。
秘訣
直方圖是最多用途且最接近於 Application Insights GetMetric 傳統 API。 Azure 監視器目前會將長條圖檢測扁平化為五種支援的彙總類型,且對百分位數的支援正在進行中。 雖然較不多才多藝,但其他 OpenTelemetry 儀器對應用程式的效能影響較小。
長條圖範例
應用程式啟動必須依名稱訂閱計量:
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Meter 必須使用相同的名稱初始化:
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new histogram metric named "FruitSalePrice".
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");
// Create a new Random object.
var rand = new Random();
// Record a few random sale prices for apples and lemons, with different colors.
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "green"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Create a new Histogram metric named "FruitSalePrice".
// This metric will track the distribution of fruit sale prices.
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");
// Create a new Random object. This object will be used to generate random sale prices.
var rand = new Random();
// Record a few random sale prices for apples and lemons, with different colors.
// Each record includes a timestamp, a value, and a set of attributes.
// The attributes can be used to filter and analyze the metric data.
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "green"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
histogram.record(1.0);
histogram.record(100.0);
histogram.record(30.0);
}
}
插入 OpenTelemetry:
建立長條圖:
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
histogram.record(1.0);
histogram.record(100.0);
histogram.record(30.0);
附註
Quarkus 社群支援並維護 Quarkus 擴充功能。 如需協助,請使用 Quarkus 社群支援管道。 Microsoft 不提供此整合的技術支援。
export class HistogramSample {
static async run() {
// Dynamically import Azure Monitor and metrics API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a histogram and record values
const meter = metrics.getMeter("testMeter");
const histogram = meter.createHistogram("histogram");
histogram.record(1, { testKey: "testValue" });
histogram.record(30, { testKey: "testValue2" });
histogram.record(100, { testKey2: "testValue" });
console.log("Histogram metrics recorded");
}
}
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
import os
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_histogram_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_histogram_demo")
# Record three values to the histogram.
histogram = meter.create_histogram("histogram")
histogram.record(1.0, {"test_key": "test_value"})
histogram.record(100.0, {"test_key2": "test_value"})
histogram.record(30.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
反例
應用程式啟動必須依名稱訂閱計量:
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Meter 必須使用相同的名稱初始化:
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new counter metric named "MyFruitCounter".
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
// Record the number of fruits sold, grouped by name and color.
myFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(1, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(2, new("name", "apple"), new("color", "green"));
myFruitCounter.Add(5, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(4, new("name", "lemon"), new("color", "yellow"));
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Create a new counter metric named "MyFruitCounter".
// This metric will track the number of fruits sold.
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
// Record the number of fruits sold, grouped by name and color.
myFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(1, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(2, new("name", "apple"), new("color", "green"));
myFruitCounter.Add(5, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(4, new("name", "lemon"), new("color", "yellow"));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
LongCounter myFruitCounter = meter
.counterBuilder("MyFruitCounter")
.build();
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "green"));
myFruitCounter.add(5, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(4, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
}
}
插入 OpenTelemetry:
建立計數器:
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
LongCounter myFruitCounter = meter.counterBuilder("MyFruitCounter")
.build();
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "green"));
myFruitCounter.add(5, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(4, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
附註
Quarkus 社群支援並維護 Quarkus 擴充功能。 如需協助,請使用 Quarkus 社群支援管道。 Microsoft 不提供此整合的技術支援。
export class CounterSample {
static async run() {
// Dynamically import Azure Monitor and metrics API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a counter and add some sample values
const meter = metrics.getMeter("otel_azure_monitor_counter_demo");
const counter = meter.createCounter("MyFruitCounter");
counter.add(1, { name: "apple", color: "red" });
counter.add(2, { name: "lemon", color: "yellow" });
counter.add(1, { name: "lemon", color: "yellow" });
counter.add(2, { name: "apple", color: "green" });
counter.add(5, { name: "apple", color: "red" });
counter.add(4, { name: "lemon", color: "yellow" });
console.log("Counter metrics recorded");
}
}
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
import os
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_counter_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_counter_demo")
# Create a counter metric with the name "counter".
counter = meter.create_counter("counter")
# Add three values to the counter.
# The first argument to the `add()` method is the value to add.
# The second argument is a dictionary of dimensions.
# Dimensions are used to group related metrics together.
counter.add(1.0, {"test_key": "test_value"})
counter.add(5.0, {"test_key2": "test_value"})
counter.add(3.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
量測計範例
應用程式啟動必須依名稱訂閱計量:
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Meter 必須使用相同的名稱初始化:
// Get the current process.
var process = Process.GetCurrentProcess();
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new observable gauge metric named "Thread.State".
// This metric will track the state of each thread in the current process.
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));
private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
// Iterate over all threads in the current process.
foreach (ProcessThread thread in process.Threads)
{
// Create a measurement for each thread, including the thread state, process ID, and thread ID.
yield return new((int)thread.ThreadState, new("ProcessId", process.Id), new("ThreadId", thread.Id));
}
}
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Get the current process.
var process = Process.GetCurrentProcess();
// Create a new observable gauge metric named "Thread.State".
// This metric will track the state of each thread in the current process.
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
// Iterate over all threads in the current process.
foreach (ProcessThread thread in process.Threads)
{
// Create a measurement for each thread, including the thread state, process ID, and thread ID.
yield return new((int)thread.ThreadState, new("ProcessId", process.Id), new("ThreadId", thread.Id));
}
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
meter.gaugeBuilder("gauge")
.buildWithCallback(
observableMeasurement -> {
double randomNumber = Math.floor(Math.random() * 100);
observableMeasurement.record(randomNumber, Attributes.of(AttributeKey.stringKey("testKey"), "testValue"));
});
}
}
插入 OpenTelemetry:
建立量測計:
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
meter.gaugeBuilder("gauge")
.buildWithCallback(
observableMeasurement -> {
double randomNumber = Math.floor(Math.random() * 100);
observableMeasurement.record(randomNumber, Attributes.of(AttributeKey.stringKey("testKey"), "testValue"));
});
附註
Quarkus 社群支援並維護 Quarkus 擴充功能。 如需協助,請使用 Quarkus 社群支援管道。 Microsoft 不提供此整合的技術支援。
export class GaugeSample {
static async run() {
// Dynamically import Azure Monitor and metrics API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create an observable gauge and register a callback
const meter = metrics.getMeter("testMeter");
const gauge = meter.createObservableGauge("gauge");
gauge.addCallback((observableResult) => {
const randomNumber = Math.floor(Math.random() * 100);
observableResult.observe(randomNumber, { testKey: "testValue" });
});
console.log("Observable gauge registered");
}
}
# Import the necessary packages.
from typing import Iterable
import os
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
from opentelemetry.metrics import CallbackOptions, Observation
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_gauge_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_gauge_demo")
# Define two observable gauge generators.
# The first generator yields a single observation with the value 9.
# The second generator yields a sequence of 10 observations with the value 9 and a different dimension value for each observation.
def observable_gauge_generator(options: CallbackOptions) -> Iterable[Observation]:
yield Observation(9, {"test_key": "test_value"})
def observable_gauge_sequence(options: CallbackOptions) -> Iterable[Observation]:
observations = []
for i in range(10):
observations.append(
Observation(9, {"test_key": i})
)
return observations
# Create two observable gauges using the defined generators.
gauge = meter.create_observable_gauge("gauge", [observable_gauge_generator])
gauge2 = meter.create_observable_gauge("gauge2", [observable_gauge_sequence])
# Wait for background execution.
input()
新增自訂例外狀況
選取檢測程式庫會自動報告 Application Insights 的例外狀況。
不過,您可能想要手動報告超出檢測程式庫報告範圍的例外狀況。
例如,您的程式碼攔截到的例外狀況通常不會報告。 您可能想要對其進行報告,以便在相關的體驗中吸引注意,包括失敗區段和端對端交易檢視。
若要使用活動記錄例外狀況:
// Start a new activity named "ExceptionExample".
using (var activity = activitySource.StartActivity("ExceptionExample"))
{
// Try to execute some code.
try
{
throw new Exception("Test exception");
}
// If an exception is thrown, catch it and set the activity status to "Error".
catch (Exception ex)
{
activity?.SetStatus(ActivityStatusCode.Error);
activity?.RecordException(ex);
}
}
若要使用 ILogger 記錄例外狀況:
// Create a logger using the logger factory. The logger category name is used to filter and route log messages.
var logger = loggerFactory.CreateLogger(logCategoryName);
// Try to execute some code.
try
{
throw new Exception("Test Exception");
}
catch (Exception ex)
{
// Log an error message with the exception. The log level is set to "Error" and the event ID is set to 0.
// The log message includes a template and a parameter. The template will be replaced with the value of the parameter when the log message is written.
logger.Log(
logLevel: LogLevel.Error,
eventId: 0,
exception: ex,
message: "Hello {name}.",
args: new object[] { "World" });
}
若要使用活動記錄例外狀況:
// Start a new activity named "ExceptionExample".
using (var activity = activitySource.StartActivity("ExceptionExample"))
{
// Try to execute some code.
try
{
throw new Exception("Test exception");
}
// If an exception is thrown, catch it and set the activity status to "Error".
catch (Exception ex)
{
activity?.SetStatus(ActivityStatusCode.Error);
activity?.RecordException(ex);
}
}
若要使用 ILogger 記錄例外狀況:
// Create a logger using the logger factory. The logger category name is used to filter and route log messages.
var logger = loggerFactory.CreateLogger("ExceptionExample");
try
{
// Try to execute some code.
throw new Exception("Test Exception");
}
catch (Exception ex)
{
// Log an error message with the exception. The log level is set to "Error" and the event ID is set to 0.
// The log message includes a template and a parameter. The template will be replaced with the value of the parameter when the log message is written.
logger.Log(
logLevel: LogLevel.Error,
eventId: 0,
exception: ex,
message: "Hello {name}.",
args: new object[] { "World" });
}
您可以使用 opentelemetry-api 來更新範圍和記錄例外狀況的狀態。
將 opentelemetry-api-1.0.0.jar (或更新版本) 新增至您的應用程式:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
將狀態設定為 error,並在程式碼中記錄例外狀況:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
將狀態設定為 error,並在程式碼中記錄例外狀況:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
Node.js SDK 只有在記錄在最上層範圍或遠端或內部範圍的子系時,才會將手動記錄的範圍型例外狀況匯出至 Application Insights。
export class CustomExceptionSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a span and record an exception
const tracer = trace.getTracer("testTracer");
const span = tracer.startSpan("hello");
try {
throw new Error("Test Error");
} catch (error) {
span.recordException(error as Error);
} finally {
span.end();
}
console.log("Exception recorded on span");
}
}
實作 OpenTelemetry Python SDK,以便自動擷取和記錄擲回的例外狀況。 如需此行為的範例,請參閱下列程式碼範例:
# Import the necessary packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Get a tracer for the current module.
tracer = trace.get_tracer("otel_azure_monitor_exception_demo")
# Exception events
try:
# Start a new span with the name "hello".
with tracer.start_as_current_span("hello") as span:
# This exception will be automatically recorded
raise Exception("Custom exception message.")
except Exception:
print("Exception raised")
如果您想要手動記錄例外狀況,您可以在內容管理員內停用該選項,並直接使用 record_exception(),如下列範例所示:
...
# Start a new span with the name "hello" and disable exception recording.
with tracer.start_as_current_span("hello", record_exception=False) as span:
try:
# Raise an exception.
raise Exception("Custom exception message.")
except Exception as ex:
# Manually record exception
span.record_exception(ex)
...
新增自訂範圍
您可能會想要在兩個案例中新增自訂範圍。 首先,檢測程式庫尚未收集相依性要求時。 其次,當您希望將應用程式流程模型化為端對端交易視圖中的一個環節時。
附註
Activity 命名空間中的 ActivitySource 和 System.Diagnostics 類別分別代表 OpenTelemetry 的 Span 和 Tracer 概念。 您可以使用其建構函式直接建立 ActivitySource,而不是使用 TracerProvider。 必須使用 ActivitySource 明確將每個 TracerProvider 類別連接到 AddSource()。 這是因為 OpenTelemetry 追蹤 API 的部分會直接併入 .NET 執行環境。 若要深入瞭解,請參閱 OpenTelemetry .NET 追蹤 API 簡介。
// Define an activity source named "ActivitySourceName". This activity source will be used to create activities for all requests to the application.
internal static readonly ActivitySource activitySource = new("ActivitySourceName");
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry tracer provider to add a source named "ActivitySourceName". This will ensure that all activities created by the activity source are traced.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddSource("ActivitySourceName"));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core application.
var app = builder.Build();
// Map a GET request to the root path ("/") to the specified action.
app.MapGet("/", () =>
{
// Start a new activity named "CustomActivity". This activity will be traced and the trace data will be sent to Azure Monitor.
using (var activity = activitySource.StartActivity("CustomActivity"))
{
// your code here
}
// Return a response message.
return $"Hello World!";
});
// Start the ASP.NET Core application.
app.Run();
StartActivity 預設為 ActivityKind.Internal,但您可以提供其他任何 ActivityKind。
ActivityKind.Client、ActivityKind.Producer 和 ActivityKind.Internal 會對應於 Application Insights dependencies。
ActivityKind.Server 和 ActivityKind.Consumer 會對應於 Application Insights requests。
附註
Activity 命名空間中的 ActivitySource 和 System.Diagnostics 類別分別代表 OpenTelemetry 的 Span 和 Tracer 概念。 您可以使用其建構函式直接建立 ActivitySource,而不是使用 TracerProvider。 必須使用 ActivitySource 明確將每個 TracerProvider 類別連接到 AddSource()。 這是因為 OpenTelemetry 追蹤 API 的部分會直接併入 .NET 執行環境。 若要深入瞭解,請參閱 OpenTelemetry .NET 追蹤 API 簡介。
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("ActivitySourceName")
.AddAzureMonitorTraceExporter()
.Build();
// Create an activity source named "ActivitySourceName".
var activitySource = new ActivitySource("ActivitySourceName");
// Start a new activity named "CustomActivity". This activity will be traced and the trace data will be sent to Azure Monitor.
using (var activity = activitySource.StartActivity("CustomActivity"))
{
// your code here
}
StartActivity 預設為 ActivityKind.Internal,但您可以提供其他任何 ActivityKind。
ActivityKind.Client、ActivityKind.Producer 和 ActivityKind.Internal 會對應於 Application Insights dependencies。
ActivityKind.Server 和 ActivityKind.Consumer 會對應於 Application Insights requests。
使用 OpenTelemetry 註釋
若要新增您自己的範圍,最簡單的方式是使用 OpenTelemetry 的 @WithSpan 注釋。
範圍會在 Application Insights 中填入 requests 和 dependencies 資料表。
將 opentelemetry-instrumentation-annotations-1.32.0.jar (或更新版本) 新增至您的應用程式:
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-annotations</artifactId>
<version>1.32.0</version>
</dependency>
每次執行您的方法時,請使用 @WithSpan 註釋發出範圍:
import io.opentelemetry.instrumentation.annotations.WithSpan;
@WithSpan(value = "your span name")
public void yourMethod() {
}
根據預設,範圍最終會在相依性類型為 dependencies 的 InProc 資料表中。
對於代表自動檢測未擷取背景工作的方法,建議將屬性 kind = SpanKind.SERVER 套用於 @WithSpan 註釋,以確保這些出現在 Application Insights requests 資料表中。
使用 OpenTelemetry API
如果上述 OpenTelemetry @WithSpan 註釋不符合您的需求,您可以使用 OpenTelemetry API 新增您的範圍。
將 opentelemetry-api-1.0.0.jar (或更新版本) 新增至您的應用程式:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
使用 GlobalOpenTelemetry 類別建立 Tracer:
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = GlobalOpenTelemetry.getTracer("com.example");
建立範圍、使其成為目前範圍,然後予以結束:
Span span = tracer.spanBuilder("my first span").startSpan();
try (Scope ignored = span.makeCurrent()) {
// do stuff within the context of this
} catch (Throwable t) {
span.recordException(t);
} finally {
span.end();
}
插入 OpenTelemetry:
建立 Tracer:
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = openTelemetry.getTracer("com.example");
建立範圍、使其成為目前範圍,然後予以結束:
Span span = tracer.spanBuilder("my first span").startSpan();
try (Scope ignored = span.makeCurrent()) {
// do stuff within the context of this
} catch (Throwable t) {
span.recordException(t);
} finally {
span.end();
}
附註
Quarkus 社群支援並維護 Quarkus 擴充功能。 如需協助,請使用 Quarkus 社群支援管道。 Microsoft 不提供此整合的技術支援。
export class CustomTraceSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a custom span, add attributes/events, then end
const tracer = trace.getTracer("otel_azure_monitor_custom_trace_demo");
const span = tracer.startSpan("doWork");
try {
span.setAttribute("component", "worker");
span.setAttribute("operation.id", "42");
span.addEvent("invoking doWork");
for (let i = 0; i < 1_000_000; i++) { /* simulate work */ }
} catch (err) {
span.recordException(err as Error);
} finally {
span.end();
}
console.log("Custom span recorded");
}
}
OpenTelemetry API 可用來新增您自己的範圍,這會出現在 Application Insights 中的 requests 和 dependencies 資料表中。
程式碼範例示範如何使用 tracer.start_as_current_span() 方法來啟動範圍、將其設為目前範圍,並在其上下文中結束範圍。
...
# Import the necessary packages.
from opentelemetry import trace
# Get a tracer for the current module.
tracer = trace.get_tracer(__name__)
# Start a new span with the name "my first span" and make it the current span.
# The "with" context manager starts, makes the span current, and ends the span within it's context
with tracer.start_as_current_span("my first span") as span:
try:
# Do stuff within the context of this span.
# All telemetry generated within this scope will be attributed to this span.
except Exception as ex:
# Record the exception on the span.
span.record_exception(ex)
...
根據預設,範圍位於具有 dependencies 相依性類型的 InProc 資料表中。
如果您的方法代表尚未被自動偵測到的背景工作,建議您設定屬性 kind = SpanKind.SERVER 以確保它出現在 Application Insights requests 資料表中。
...
# Import the necessary packages.
from opentelemetry import trace
from opentelemetry.trace import SpanKind
# Get a tracer for the current module.
tracer = trace.get_tracer(__name__)
# Start a new span with the name "my request span" and the kind set to SpanKind.SERVER.
with tracer.start_as_current_span("my request span", kind=SpanKind.SERVER) as span:
# Do stuff within the context of this span.
...
傳送自訂事件
Application Insights 會將自定義事件儲存在數據表中 customEvents 。
分析、篩選和可視化的其中一種方法是使用Application Insights使用體驗。
如果您想要將用戶端互動事件的集合自動化,您可以在 JavaScript SDK 中使用外掛程式。
自定義事件處於公開預覽狀態,並使用 Azure.Monitor.OpenTelemetry.AspNetCore 1.3.0-beta.3。
若要使用 CustomEvent傳送 ILogger ,請在訊息範本中設定 "microsoft.custom_event.name" 屬性。
// Create a logger factory and configure OpenTelemetry with Azure Monitor
var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter();
});
});
// Create a logger for the specified category
var logger = loggerFactory.CreateLogger(logCategoryName);
// Log a custom event with a custom name and additional attribute
// The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}", "test-event-name", "val1");
自定義事件處於公開預覽狀態,並使用 Azure.Monitor.OpenTelemetry.Exporter 1.4.0-beta.3。
若要使用 CustomEvent傳送 ILogger ,請在訊息範本中設定 "microsoft.custom_event.name" 屬性。
// Create a logger factory and configure OpenTelemetry with Azure Monitor
var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter();
});
});
// Create a logger for the specified category
var logger = loggerFactory.CreateLogger(logCategoryName);
// Log a custom event with a custom name and additional attribute
// The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}", "test-event-name", "val1");
若要使用 Java 代理程式傳送 customEvent ,請在 OpenTelemetry 記錄檔記錄上設定 "microsoft.custom_event.name" 屬性。
根據是否使用 Application Insights Java 代理或自動配置 SDK,擷取 OpenTelemetry 記錄器的方式會稍有不同。 下列範例會進一步說明此詳細數據。
針對 Application Insights JAVA 代理程式:
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.logs.Logger;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.logs.Severity;
Logger logger = GlobalOpenTelemetry.get().getLogsBridge().get("opentelemetry-logger");
logger.logRecordBuilder()
.setAttribute(AttributeKey.stringKey("microsoft.custom_event.name"),"test-event-name")
.setSeverity(Severity.INFO)
.emit();
針對自動設定 SDK:
import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigure;
import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigureOptions;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.logs.Logger;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder;
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorAutoConfigureOptions options = new AzureMonitorAutoConfigureOptions();
options.connectionString("<your connection string>");
AzureMonitorAutoConfigure.customize(sdkBuilder, options);
OpenTelemetry openTelemetry = sdkBuilder.build().getOpenTelemetrySdk();
Logger logger = openTelemetry.getLogsBridge().get("opentelemetry-logger");
logger.logRecordBuilder()
.setAttribute(AttributeKey.stringKey("microsoft.custom_event.name"),"test-event-name")
.setSeverity(Severity.INFO)
.emit();
若要可靠地發出自定義事件,請直接使用 OpenTelemetry API。 某些記錄架構不支援附加或剖析自定義事件屬性。
您無法在 JAVA 原生中使用 customEvent 屬性傳送 "microsoft.custom_event.name"。
若要使用 customEvent 傳送 logger.emit ,請在記錄的 "microsoft.custom_event.name" 物件中設定 attributes 屬性。 您也可以視需要包含其他屬性。
export class CustomEventSample {
static async run() {
// Dynamically import Azure Monitor and the OpenTelemetry logs API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { logs, SeverityNumber } = await import("@opentelemetry/api-logs");
// Initialize Azure Monitor (enables logs bridge)
const monitor = useAzureMonitor();
// Get a logger and emit a customEvent by setting the microsoft attribute key
const logger = logs.getLogger("my-app-logger");
logger.emit({
body: "Hello World!",
severityNumber: SeverityNumber.INFO,
attributes: {
"microsoft.custom_event.name": "test-event-name",
"additional_attrs": "val1",
},
});
// Example: populate client_IP via attribute 'client.address'
logger.emit({
body: "This entry will have a custom client_IP",
severityNumber: SeverityNumber.INFO,
attributes: {
"microsoft.custom_event.name": "test_event",
"client.address": "192.168.1.1",
},
});
console.log("Custom events emitted");
}
}
若要在 Python 中傳送 customEvent,請使用 logging 套件並在 "microsoft.custom_event.name" 參數中使用 extra 屬性。
import logging
from azure.monitor.opentelemetry import configure_azure_monitor
# Set up your application logger
logger = logging.getLogger("my-app-logger")
# Configure Azure Monitor to collect logs from the specified logger name
configure_azure_monitor(
logger_name="my-app-logger", # Collect logs from your namespaced logger
)
# Log a custom event with a custom name and additional attribute
# The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.warning(
"Hello World!",
extra={
"microsoft.custom_event.name": "test-event-name",
"additional_attrs": "val1"
}
)
# You can also populate fields like client_IP with attribute `client.address`
logger.info(
"This entry will have a custom client_IP",
extra={
"microsoft.custom_event.name": "test_event",
"client.address": "192.168.1.1"
}
)
修改遙測
本節說明如何修改遙測。
新增範圍屬性
這些屬性可能包括將自訂屬性新增至遙測數據。 您也可以使用屬性來設定 Application Insights 結構描述中的選用欄位,例如用戶端 IP。
將自訂屬性新增至範圍
您新增至範圍的任何 屬性 會匯出為自訂屬性。 他們會在要求、相依性、追蹤或例外狀況數據表中填入 customDimensions 字段。
若要新增範圍屬性,請使用下列兩種方式之一:
許多檢測程式庫都提供擴充選項。 如需指引,請參閱各個工具庫的讀我檔案。
使用自訂處理器:
秘訣
請在新增 Azure 監視器之前,先新增這裡顯示的處理器。
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry tracer provider to add a new processor named ActivityEnrichingProcessor.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddProcessor(new ActivityEnrichingProcessor()));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core application.
var app = builder.Build();
// Start the ASP.NET Core application.
app.Run();
使用下列程式碼,將 ActivityEnrichingProcessor.cs 新增至您的專案:
public class ActivityEnrichingProcessor : BaseProcessor<Activity>
{
public override void OnEnd(Activity activity)
{
// The updated activity will be available to all processors which are called after this processor.
activity.DisplayName = "Updated-" + activity.DisplayName;
activity.SetTag("CustomDimension1", "Value1");
activity.SetTag("CustomDimension2", "Value2");
}
}
若要新增範圍屬性,請使用下列兩種方式之一:
- 使用檢測程式庫所提供的選項。
- 新增自訂範圍處理器。
秘訣
使用檢測程式庫所提供的選項的優點 (如果有) 是整個上下文都可用。 因此,使用者可以選取要新增或篩選更多屬性。 例如,HttpClient 檢測程式庫中的擴充選項可讓使用者存取 HTTPRequestMessage 本身。 使用者可以從中選取任何部分並儲存為屬性。
許多檢測程式庫都提供擴充選項。 如需指引,請參閱各個工具庫的讀我檔案。
使用自訂處理器:
秘訣
在 Azure 監視器匯出工具之前新增此處顯示的處理器。
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
// Add a source named "OTel.AzureMonitor.Demo".
.AddSource("OTel.AzureMonitor.Demo") // Add a new processor named ActivityEnrichingProcessor.
.AddProcessor(new ActivityEnrichingProcessor()) // Add the Azure Monitor trace exporter.
.AddAzureMonitorTraceExporter() // Add the Azure Monitor trace exporter.
.Build();
使用下列程式碼,將 ActivityEnrichingProcessor.cs 新增至您的專案:
public class ActivityEnrichingProcessor : BaseProcessor<Activity>
{
// The OnEnd method is called when an activity is finished. This is the ideal place to enrich the activity with additional data.
public override void OnEnd(Activity activity)
{
// Update the activity's display name.
// The updated activity will be available to all processors which are called after this processor.
activity.DisplayName = "Updated-" + activity.DisplayName;
// Set custom tags on the activity.
activity.SetTag("CustomDimension1", "Value1");
activity.SetTag("CustomDimension2", "Value2");
}
}
您可以使用 opentelemetry-api 將屬性新增至範圍。
新增一或多個範圍屬性會在 customDimensions、requests、dependencies 或 traces 資料表中填入 exceptions 欄位。
將 opentelemetry-api-1.0.0.jar (或更新版本) 新增至您的應用程式:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
在您的程式碼中新增自訂維度:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
在您的程式碼中新增自訂維度:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
export class SpanAttributeEnrichmentSample {
static async run() {
// Dynamically import the Azure Monitor integration
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
// Create a SpanEnrichingProcessor to add custom dimensions
class SpanEnrichingProcessor {
forceFlush() { return Promise.resolve(); }
shutdown() { return Promise.resolve(); }
onStart() {}
onEnd(span: any) {
(span as any).attributes = (span as any).attributes || {};
(span as any).attributes["CustomDimension1"] = "value1";
(span as any).attributes["CustomDimension2"] = "value2";
}
}
// Initialize Azure Monitor with the custom processor
const monitor = useAzureMonitor({
spanProcessors: [new SpanEnrichingProcessor()],
});
console.log("Span enrichment processor registered");
}
}
使用自訂處理器:
...
# Import the necessary packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Create a SpanEnrichingProcessor instance.
span_enrich_processor = SpanEnrichingProcessor()
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
# Configure the custom span processors to include span enrich processor.
span_processors=[span_enrich_processor],
)
...
使用下列程式碼,將 SpanEnrichingProcessor 新增至您的專案:
# Import the SpanProcessor class from the opentelemetry.sdk.trace module.
from opentelemetry.sdk.trace import SpanProcessor
class SpanEnrichingProcessor(SpanProcessor):
def on_end(self, span):
# Prefix the span name with the string "Updated-".
span._name = "Updated-" + span.name
# Add the custom dimension "CustomDimension1" with the value "Value1".
span._attributes["CustomDimension1"] = "Value1"
# Add the custom dimension "CustomDimension2" with the value "Value2".
span._attributes["CustomDimension2"] = "Value2"
設定使用者 IP
您可以透過在 span 上設定屬性,以填入請求的 client_IP 欄位。 Application Insights 會使用IP位址來產生使用者位置屬性,然後 依預設捨棄它。
使用 自訂屬性範例,但在 ActivityEnrichingProcessor.cs中取代以下程式碼行:
// Add the client IP address to the activity as a tag.
// only applicable in case of activity.Kind == Server
activity.SetTag("client.address", "<IP Address>");
使用 自訂屬性範例,但在 ActivityEnrichingProcessor.cs中取代以下程式碼行:
// Add the client IP address to the activity as a tag.
// only applicable in case of activity.Kind == Server
activity.SetTag("client.address", "<IP Address>");
使用 自訂屬性範例,但取代下列幾行程式代碼:
export class SetUserIpSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor();
// Framework-agnostic helper to set client IP on the active server span
const setIpForRequest = (clientIp: string) => {
const span = trace.getActiveSpan();
if (span) {
// Preferred attribute for client IP
span.setAttribute("client.address", clientIp);
// Optional: legacy/alternate attribute
span.setAttribute("http.client_ip", clientIp);
}
};
// Call setIpForRequest("<IP Address>") from within your web framework's request pipeline
console.log("Use setIpForRequest('<IP Address>') inside your request handler to stamp the active span.");
}
}
使用 自訂屬性範例,但在 SpanEnrichingProcessor.py中取代以下程式碼行:
# Set the `http.client_ip` attribute of the span to the specified IP address.
span._attributes["http.client_ip"] = "<IP Address>"
設定使用者識別碼或已驗證的使用者識別碼
您可以使用下列指引填入要求的 user_Id 或 user_AuthenticatedId 欄位。 使用者識別碼是匿名使用者識別碼。 已驗證的使用者識別碼是已知的使用者識別碼。
重要
在您設定已驗證的使用者識別碼之前,請參閱適用的隱私權法律。
使用 自訂屬性範例:
// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<User Id>");
使用 自訂屬性範例:
// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<User Id>");
在 user ID、requests 或 dependencies 資料表中填入 exceptions 欄位。
將 opentelemetry-api-1.0.0.jar (或更新版本) 新增至您的應用程式:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
在您的程式碼中設定 user_Id:
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser"); // (user_AuthenticatedId)
Span.current().setAttribute("enduser.pseudo.id", "myuser"); // (user_Id)
在 user ID、requests 或 dependencies 資料表中填入 exceptions 欄位。
在您的程式碼中設定 user_Id:
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser"); // (user_AuthenticatedId)
Span.current().setAttribute("enduser.pseudo.id", "myuser"); // (user_Id)
使用 自訂屬性範例,但取代下列幾行程式代碼:
export class SetUserIdSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor();
// Framework-agnostic helper to set user identifiers on the active server span
const setUserForRequest = (authenticatedId?: string, anonymousId?: string) => {
const span = trace.getActiveSpan();
if (span) {
if (authenticatedId) span.setAttribute("enduser.id", authenticatedId); // user_AuthenticatedId
if (anonymousId) span.setAttribute("enduser.pseudo.id", anonymousId); // user_Id
}
};
// Call setUserForRequest("<authenticated-id>", "<anonymous-id>") inside your request handler
console.log("Use setUserForRequest('<auth-id>', '<anon-id>') inside your request handler to stamp the active span.");
}
}
使用 自訂屬性範例,但取代下列幾行程式代碼:
# Set the `enduser.id` attribute of the span to the specified user ID.
span._attributes["enduser.id"] = "<User ID>"
新增記錄屬性
OpenTelemetry 使用。NET 的 ILogger。
您可以使用 訊息範本將自訂維度附加至記錄。
OpenTelemetry 使用。NET 的 ILogger。
您可以使用 訊息範本將自訂維度附加至記錄。
Logback、Log4j 和 java.util.logging 會自動檢測。 您可以透過下列方式,將自訂維度附加至記錄:
若是 Spring Boot 原生應用程式,則會立即檢測 Logback。
export class BunyanLogAttributesSample {
static async run() {
// Dynamically import Azure Monitor and Bunyan
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const bunyanMod = await import("bunyan");
const bunyan = (bunyanMod as any).default ?? bunyanMod;
// Enable Azure Monitor integration and bunyan instrumentation
const monitor = useAzureMonitor({
instrumentationOptions: { bunyan: { enabled: true } },
});
// Emit a log with custom attributes
const log = (bunyan as any).createLogger({ name: "testApp" });
log.info({ key1: "value1", feature: "demo" }, "Warning log with properties");
console.log("Bunyan log with attributes emitted");
}
}
系統會自動檢測 Python 記錄程式庫。 您可以將字典傳遞至記錄的 extra 引數,以便將自訂維度附加至記錄:
...
# Create a warning log message with the properties "key1" and "value1".
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
取得追蹤識別碼或範圍識別碼
您可以使用下列步驟來取得目前使用中 Span 的 Trace ID 和 Span ID。
附註
Activity 命名空間中的 ActivitySource 和 System.Diagnostics 類別分別代表 OpenTelemetry 的 Span 和 Tracer 概念。 這是因為 OpenTelemetry 追蹤 API 的部分會直接併入 .NET 執行環境。 若要深入瞭解,請參閱 OpenTelemetry .NET 追蹤 API 簡介。
// Get the current activity.
Activity activity = Activity.Current;
// Get the trace ID of the activity.
string traceId = activity?.TraceId.ToHexString();
// Get the span ID of the activity.
string spanId = activity?.SpanId.ToHexString();
附註
Activity 命名空間中的 ActivitySource 和 System.Diagnostics 類別分別代表 OpenTelemetry 的 Span 和 Tracer 概念。 這是因為 OpenTelemetry 追蹤 API 的部分會直接併入 .NET 執行環境。 若要深入瞭解,請參閱 OpenTelemetry .NET 追蹤 API 簡介。
// Get the current activity.
Activity activity = Activity.Current;
// Get the trace ID of the activity.
string traceId = activity?.TraceId.ToHexString();
// Get the span ID of the activity.
string spanId = activity?.SpanId.ToHexString();
您可以使用 opentelemetry-api 來取得追蹤識別碼或範圍識別碼。
將 opentelemetry-api-1.0.0.jar (或更新版本) 新增至您的應用程式:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
取得程式碼中的要求追蹤識別碼和範圍識別碼:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
取得程式碼中的要求追蹤識別碼和範圍識別碼:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
取得程式碼中的要求追蹤識別碼和範圍識別碼:
export class GetTraceAndSpanIdSample {
static async run() {
// Dynamically import tracing API
const { trace } = await import("@opentelemetry/api");
// Read the span/trace id from the active span (if any)
const activeSpan = trace.getActiveSpan();
const spanId = activeSpan?.spanContext().spanId;
const traceId = activeSpan?.spanContext().traceId;
console.log("SpanId:", spanId, "TraceId:", traceId);
}
}
取得程式碼中的要求追蹤識別碼和範圍識別碼:
# Import the necessary libraries.
from opentelemetry import trace
# Get the trace ID and span ID of the current span.
trace_id = trace.get_current_span().get_span_context().trace_id
span_id = trace.get_current_span().get_span_context().span_id
下一步
附註
Quarkus 社群支援並維護 Quarkus 擴充功能。 如需協助,請使用 Quarkus 社群支援管道。 Microsoft 不提供此整合的技術支援。