本指南說明如何使用 Azure 監視器 OpenTelemetry 散發版本在 Azure 監視器 Application Insights 中設定 OpenTelemetry (OTel)。 適當的設定可確保跨 .NET、Java、Node.js和 Python 應用程式進行一致的遙測數據收集,以便進行更可靠的監視和診斷。
連接字串
Application Insights 中的連接字串會定義傳送遙測資料的目標位置。
使用下列三種方式之一來設定連接字串:
把它加 UseAzureMonitor() 到你的 program.cs 檔案裡。
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
options.ConnectionString = "<YOUR-CONNECTION-STRING>";
});
var app = builder.Build();
app.Run();
設定環境變數。
APPLICATIONINSIGHTS_CONNECTION_STRING=<YOUR-CONNECTION-STRING>
將下列區段新增至 appsettings.json 組態檔。
{
"AzureMonitor": {
"ConnectionString": "<YOUR-CONNECTION-STRING>"
}
}
附註
如果您在多個位置設定連接字串,我們會遵循下列優先順序:
- Code
- 環境變數
- 組態檔
使用下列兩種方式之一來設定連接字串:
將 Azure 監視器匯出工具新增至應用程式啟動時的每個 OpenTelemetry 訊號。
// Create a new OpenTelemetry tracer provider.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter(options =>
{
options.ConnectionString = "<YOUR-CONNECTION-STRING>";
})
.Build();
// Create a new OpenTelemetry meter provider.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddAzureMonitorMetricExporter(options =>
{
options.ConnectionString = "<YOUR-CONNECTION-STRING>";
})
.Build();
// Create a new logger factory.
// It is important to keep the LoggerFactory instance active throughout the process lifetime.
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddOpenTelemetry(logging =>
{
logging.AddAzureMonitorLogExporter(options =>
{
options.ConnectionString = "<YOUR-CONNECTION-STRING>";
});
});
});
設定環境變數。
APPLICATIONINSIGHTS_CONNECTION_STRING=<YOUR-CONNECTION-STRING>
附註
如果您在多個位置設定連接字串,我們會遵循下列優先順序:
- Code
- 環境變數
使用下列兩種方式之一來設定連接字串:
設定環境變數。
APPLICATIONINSIGHTS_CONNECTION_STRING=<YOUR-CONNECTION-STRING>
使用設定物件。
export class BasicConnectionSample {
static async run() {
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const options = {
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<YOUR-CONNECTION-STRING>",
},
};
const monitor = useAzureMonitor(options);
console.log("Azure Monitor initialized");
}
}
使用下列兩種方式之一來設定連接字串:
設定環境變數。
APPLICATIONINSIGHTS_CONNECTION_STRING=<YOUR-CONNECTION-STRING>
使用函數 configure_azure_monitor 。
# Import the `configure_azure_monitor()` function from the `azure.monitor.opentelemetry` package.
from azure.monitor.opentelemetry import configure_azure_monitor
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<YOUR-CONNECTION-STRING>` with the connection string of your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<YOUR-CONNECTION-STRING>",
)
設定雲端角色名稱和雲端角色執行個體
針對 支援的語言,Azure 監視器 OpenTelemetry Distro 會自動偵測資源內容,並提供您元件的 雲端角色名稱和 雲端角色實例屬性的預設值。 不過,您可能想要將預設值覆寫為對您的小組有意義的值。 雲端角色名稱的值會顯示在應用程式地圖上作為節點下方的名稱。
透過 資源 屬性設定雲端角色名稱和雲端角色實例。 雲端角色名稱會使用 service.namespace 和 service.name 屬性,但如果 service.name 未設定,則會回復為 service.namespace。 雲端角色執行個體會使用 service.instance.id 屬性值。 如需資源標準屬性的詳細資訊,請參閱 OpenTelemetry Semantic 慣例。
// Setting role name and role instance
// Create a dictionary of resource attributes.
var resourceAttributes = new Dictionary<string, object> {
{ "service.name", "my-service" },
{ "service.namespace", "my-namespace" },
{ "service.instance.id", "my-instance" }};
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry()
.UseAzureMonitor()
// Configure the ResourceBuilder to add the custom resource attributes to all signals.
// Custom resource attributes should be added AFTER AzureMonitor to override the default ResourceDetectors.
.ConfigureResource(resourceBuilder => resourceBuilder.AddAttributes(resourceAttributes));
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
透過 資源 屬性設定雲端角色名稱和雲端角色實例。 雲端角色名稱會使用 service.namespace 和 service.name 屬性,但如果 service.name 未設定,則會回復為 service.namespace。 雲端角色執行個體會使用 service.instance.id 屬性值。 如需資源標準屬性的詳細資訊,請參閱 OpenTelemetry Semantic 慣例。
// Setting role name and role instance
// Create a dictionary of resource attributes.
var resourceAttributes = new Dictionary<string, object> {
{ "service.name", "my-service" },
{ "service.namespace", "my-namespace" },
{ "service.instance.id", "my-instance" }};
// Create a resource builder.
var resourceBuilder = ResourceBuilder.CreateDefault().AddAttributes(resourceAttributes);
// Create a new OpenTelemetry tracer provider and set the resource builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
// Set ResourceBuilder on the TracerProvider.
.SetResourceBuilder(resourceBuilder)
.AddAzureMonitorTraceExporter()
.Build();
// Create a new OpenTelemetry meter provider and set the resource builder.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
// Set ResourceBuilder on the MeterProvider.
.SetResourceBuilder(resourceBuilder)
.AddAzureMonitorMetricExporter()
.Build();
// Create a new logger factory and add the OpenTelemetry logger provider with the resource builder.
// It is important to keep the LoggerFactory instance active throughout the process lifetime.
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddOpenTelemetry(logging =>
{
// Set ResourceBuilder on the Logging config.
logging.SetResourceBuilder(resourceBuilder);
logging.AddAzureMonitorLogExporter();
});
});
若要設定雲端角色名稱:
- 使用
spring.application.name Spring Boot 原生映像應用程式。
- 將
quarkus.application.name 用於 Quarkus 原生映像應用程式。
附註
Quarkus 社群支援並維護 Quarkus 擴充功能。 如需協助,請使用 Quarkus 社群支援管道。 Microsoft 不提供此整合的技術支援。
透過 資源 屬性設定雲端角色名稱和雲端角色實例。 雲端角色名稱會使用 service.namespace 和 service.name 屬性,但如果 service.name 未設定,則會回復為 service.namespace。 雲端角色執行個體會使用 service.instance.id 屬性值。 如需資源標準屬性的詳細資訊,請參閱 OpenTelemetry Semantic 慣例。
export class CloudRoleSample {
static async run() {
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { resourceFromAttributes } = await import("@opentelemetry/resources");
const { ATTR_SERVICE_NAME } = await import("@opentelemetry/semantic-conventions");
const { ATTR_SERVICE_NAMESPACE, ATTR_SERVICE_INSTANCE_ID } =
await import("@opentelemetry/semantic-conventions/incubating");
const customResource = resourceFromAttributes({
[ATTR_SERVICE_NAME]: process.env.OTEL_SERVICE_NAME || "my-service",
[ATTR_SERVICE_NAMESPACE]: process.env.OTEL_SERVICE_NAMESPACE || "my-namespace",
[ATTR_SERVICE_INSTANCE_ID]: process.env.OTEL_SERVICE_INSTANCE_ID || "my-instance",
});
const options = {
resource: customResource,
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<YOUR-CONNECTION-STRING>",
},
};
const monitor = useAzureMonitor(options);
console.log("Azure Monitor initialized (custom resource)");
}
}
透過 資源 屬性設定雲端角色名稱和雲端角色實例。 雲端角色名稱會使用 service.namespace 和 service.name 屬性,但如果 service.name 未設定,則會回復為 service.namespace。 雲端角色執行個體會使用 service.instance.id 屬性值。 如需資源標準屬性的詳細資訊,請參閱 OpenTelemetry Semantic 慣例。
使用 OTEL_RESOURCE_ATTRIBUTES 和/或 OTEL_SERVICE_NAME 環境變數來設定資源屬性。
OTEL_RESOURCE_ATTRIBUTES 會採用一系列以逗號分隔的索引鍵/值組。 例如,若要將 [雲端角色名稱] 設定為 my-namespace.my-helloworld-service,並將 [雲端角色執行個體] 設定為 my-instance,您可以設定 OTEL_RESOURCE_ATTRIBUTES 和 OTEL_SERVICE_NAME,如下所示:
export OTEL_RESOURCE_ATTRIBUTES="service.namespace=my-namespace,service.instance.id=my-instance"
export OTEL_SERVICE_NAME="my-helloworld-service"
如果您未設定 service.namespace 資源屬性,您也可以只使用 OTEL_SERVICE_NAME 環境變數或 service.name 資源屬性來設定 [雲端角色名稱]。 例如,若要將 [雲端角色名稱] 設定為 my-helloworld-service,並將 [雲端角色執行個體] 設定為 my-instance,您可以設定 OTEL_RESOURCE_ATTRIBUTES 和 OTEL_SERVICE_NAME,如下所示:
export OTEL_RESOURCE_ATTRIBUTES="service.instance.id=my-instance"
export OTEL_SERVICE_NAME="my-helloworld-service"
啟用取樣
取樣會降低遙測數據的吞取量與成本。 Azure Monitor 的 OpenTelemetry 發行版支援兩種追蹤取樣策略,並且(可選地)讓你將應用程式日誌與追蹤取樣決策對齊。 取樣器會將選定的取樣比率或速率附加到匯出的區段,讓 Application Insights 能準確調整經驗數。 欲了解概念性概述,請參閱 了解更多關於抽樣的資訊。
重要
- 取樣決策適用於追蹤 (範圍)。
- 指標從不抽樣。
-
日誌 預設不會被取樣。 你可以選擇對 日誌採用基於痕跡的取樣 ,這樣屬於未取樣痕跡的日誌就會被刪除。 欲了解更多細節, 請設定日誌的追蹤取樣。
使用標準的 OpenTelemetry 環境變數選擇取樣器並提供其參數:
以下範例展示了如何利用環境變數配置取樣。
固定百分比抽樣(~10%)
export OTEL_TRACES_SAMPLER="microsoft.fixed.percentage"
export OTEL_TRACES_SAMPLER_ARG=0.1
速率限制取樣(~1.5 trace/sec)
export OTEL_TRACES_SAMPLER="microsoft.rate_limited"
export OTEL_TRACES_SAMPLER_ARG=1.5
附註
當同時設定程式碼層級的選項與環境變數時, 環境變數會優先。 預設取樣器的行為會因語言而異,請參見以下分頁。
固定百分比抽樣
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenTelemetry().UseAzureMonitor(o =>
{
o.SamplingRatio = 0.1F; // ~10%
});
var app = builder.Build();
app.Run();
速率限制取樣
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenTelemetry().UseAzureMonitor(o =>
{
o.TracesPerSecond = 1.5; // ~1.5 traces/sec
});
var app = builder.Build();
app.Run();
附註
如果你沒有在程式碼或環境變數中設定取樣器,Azure Monitor 預設會使用 ApplicationInsightsSampler 。
固定百分比抽樣
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter(o => o.SamplingRatio = 0.1F)
.Build();
速率限制取樣
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter(o => o.TracesPerSecond = 1.5F)
.Build();
附註
如果你沒有在程式碼或環境變數中設定取樣器,Azure Monitor 預設會使用 ApplicationInsightsSampler 。
從 3.4.0 開始,預設 採用速率限制抽樣。 關於設定選項與範例,請參見 Java 取樣。
固定百分比抽樣
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const monitor = useAzureMonitor({
samplingRatio: 0.1, // ~10%
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<YOUR-CONNECTION-STRING>",
},
});
速率限制取樣
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const monitor = useAzureMonitor({
tracesPerSecond: 1.5, // ~1.5 traces/sec
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<YOUR-CONNECTION-STRING>",
},
});
附註
如果你沒有在程式碼或環境變數中設定取樣器,Azure Monitor 預設會使用 ApplicationInsightsSampler 。
固定百分比抽樣
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor(
connection_string="<YOUR-CONNECTION-STRING>",
sampling_ratio=0.1, # 0.1 = 10% of traces sampled
)
速率限制取樣
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor(
connection_string="<YOUR-CONNECTION-STRING>",
traces_per_second=1.5, # ~1.5 traces/sec
)
附註
如果你沒有設定任何環境變數,或沒有提供sampling_ratio或traces_per_second其中之一,configure_azure_monitor()會預設使用ApplicationInsightsSampler。
秘訣
使用固定百分比抽樣且不確定取樣率設定時,建議從 5%0.05( )。 根據故障與效能面板中顯示的操作準確度調整速率。 任何抽樣都會降低準確度,因此我們建議在 OpenTelemetry 指標上發出警示,因為這些指標不會受到抽樣影響。
啟用後,屬於 未取樣痕跡 的日誌紀錄會被刪除,以確保日誌與痕跡取樣保持一致。
- 當日誌記錄具有有效的
SpanId時,該記錄被視為追蹤的一部分。
- 若關聯的追蹤
TraceFlags 顯示 未取樣,日誌紀錄將 被丟棄。
-
沒有任何痕跡上下文的日誌記錄不會受影響。
- 此功能 預設是關閉的。 賦能即語言,請參見以下標籤。
在您的設定中請使用以下設定來啟用基於痕跡的日誌取樣:
builder.Services.AddOpenTelemetry().UseAzureMonitor(o =>
{
o.EnableTraceBasedLogsSampler = true;
});
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter(o => o.EnableTraceBasedLogsSampler = true)
.Build();
對於 Java 應用程式,基於追蹤的取樣預設是啟用的。
對於 Spring Boot 原生及 Quarkus 原生應用程式,預設啟用基於追蹤的取樣功能。
附註
Quarkus 社群支援並維護 Quarkus 擴充功能。 如需協助,請使用 Quarkus 社群支援管道。 Microsoft 不提供此整合的技術支援。
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const monitor = useAzureMonitor({
enableTraceBasedSamplingForLogs: true,
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<YOUR-CONNECTION-STRING>",
},
});
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor(
connection_string="<YOUR-CONNECTION-STRING>",
enable_trace_based_sampling_for_logs=True,
)
即時計量
即時計量 提供即時分析儀錶板,以深入瞭解應用程式活動和效能。
此功能預設為啟用。
設定 Distro 時,使用者可以停用即時計量。
builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
// Disable the Live Metrics feature.
options.EnableLiveMetrics = false;
});
此功能不適用於 Azure 監視器 .NET 匯出工具。
Live Metrics 目前不適用於 GraalVM 原生應用程式。
當使用者使用 enableLiveMetrics 屬性設定 Distro 時,可以啟用/停用即時計量。
export class LiveMetricsSample {
static async run() {
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const options = {
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<YOUR-CONNECTION-STRING>",
},
enableLiveMetrics: true, // set to false to disable
};
const monitor = useAzureMonitor(options);
console.log("Azure Monitor initialized (live metrics enabled)");
}
}
您可以使用適用於 Python 的 Azure 監視器 OpenTelemetry Distro 來啟用即時計量,如下所示:
...
configure_azure_monitor(
enable_live_metrics=True
)
...
您可能想要啟用 Microsoft Entra 驗證,以建立更安全的 Azure 連線,防止未經授權的遙測擷取到您的訂用帳戶。
如需詳細資訊,請參閱我們針對每個支援的語言連結的專用Microsoft Entra 驗證頁面。
Microsoft Entra ID 驗證不適用於 GraalVM 原生應用程式。
離線儲存和自動重試
當應用程式與 Application Insights 中斷連線時,Azure Monitor 基於 OpenTelemetry 的解決方案會暫存遙測資料,並在最多 48 小時內重試傳送。 如需數據處理建議,請參閱 匯出和刪除私人數據。 高負載應用程式偶爾會因為以下兩個原因而捨棄遙測資料:超過允許的時間或超過最大檔案大小。 必要時,產品會將最近的事件優先於舊事件。
發行版本套件包含 AzureMonitorExporter,預設會針對離線儲存使用下列其中一個位置 (依優先順序列出):
窗戶
- %LOCALAPPDATA%\Microsoft\AzureMonitor
- %TEMP%\Microsoft\AzureMonitor
非 Windows 版本
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
- /tmp/Microsoft/AzureMonitor
若要覆寫預設的目錄,您應該設定 AzureMonitorOptions.StorageDirectory。
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options =>
{
// Set the Azure Monitor storage directory to "C:\\SomeDirectory".
// This is the directory where the OpenTelemetry SDK will store any telemetry data that can't be sent to Azure Monitor immediately.
options.StorageDirectory = "C:\\SomeDirectory";
});
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
若要停用此功能,您應該設定 AzureMonitorOptions.DisableOfflineStorage = true。
依預設,AzureMonitorExporter 會使用下列其中一個位置來進行離線儲存 (按優先順序列出):
窗戶
- %LOCALAPPDATA%\Microsoft\AzureMonitor
- %TEMP%\Microsoft\AzureMonitor
非 Windows 系統
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
- /tmp/Microsoft/AzureMonitor
若要覆寫預設的目錄,您應該設定 AzureMonitorExporterOptions.StorageDirectory。
// Create a new OpenTelemetry tracer provider and set the storage directory.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter(options =>
{
// Set the Azure Monitor storage directory to "C:\\SomeDirectory".
// This is the directory where the OpenTelemetry SDK will store any trace data that can't be sent to Azure Monitor immediately.
options.StorageDirectory = "C:\\SomeDirectory";
})
.Build();
// Create a new OpenTelemetry meter provider and set the storage directory.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddAzureMonitorMetricExporter(options =>
{
// Set the Azure Monitor storage directory to "C:\\SomeDirectory".
// This is the directory where the OpenTelemetry SDK will store any metric data that can't be sent to Azure Monitor immediately.
options.StorageDirectory = "C:\\SomeDirectory";
})
.Build();
// Create a new logger factory and add the OpenTelemetry logger provider with the storage directory.
// It is important to keep the LoggerFactory instance active throughout the process lifetime.
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddOpenTelemetry(logging =>
{
logging.AddAzureMonitorLogExporter(options =>
{
// Set the Azure Monitor storage directory to "C:\\SomeDirectory".
// This is the directory where the OpenTelemetry SDK will store any log data that can't be sent to Azure Monitor immediately.
options.StorageDirectory = "C:\\SomeDirectory";
});
});
});
若要停用此功能,您應該設定 AzureMonitorExporterOptions.DisableOfflineStorage = true。
當代理程式無法將遙測傳送至 Azure 監視器時,它會將遙測檔案儲存在磁碟上。 這些檔案會儲存在系統屬性 telemetry 所指定的目錄下的 java.io.tmpdir 資料夾。 每個檔名的開頭都是時間戳,並以 .trn 副檔名結尾。 此離線儲存機制有助於確保遙測數據會在暫時網路中斷或資料接收失敗期間保留。
代理程式預設最多會儲存 50 MB 的遙測數據,並允許 設定記憶體限制。 我們會定期嘗試發送已儲存的遙測數據。 刪除超過 48 小時的遙測檔案,並在達到儲存限制時捨棄最舊的事件。
如需可用組態的完整清單,請參閱 組態選項。
當代理程式無法將遙測傳送至 Azure 監視器時,它會將遙測檔案儲存在磁碟上。 這些檔案會儲存在系統屬性 telemetry 所指定的目錄下的 java.io.tmpdir 資料夾。 每個檔名的開頭都是時間戳,並以 .trn 副檔名結尾。 此離線儲存機制有助於確保遙測數據會在暫時網路中斷或資料接收失敗期間保留。
代理程式預設最多會儲存 50 MB 的遙測數據。 我們會定期嘗試發送已儲存的遙測數據。 刪除超過 48 小時的遙測檔案,並在達到儲存限制時捨棄最舊的事件。
依預設,AzureMonitorExporter 會使用下列其中一個位置來進行離線儲存 (按優先順序列出):
窗戶
- %TEMP%\Microsoft\AzureMonitor
非 Windows 版本
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
若要覆寫預設的目錄,您應該設定 storageDirectory。
例如:
export class OfflineStorageSample {
static async run() {
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const options = {
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<YOUR-CONNECTION-STRING>",
storageDirectory: "C:\\\\SomeDirectory",
disableOfflineStorage: false, // set to true to disable
},
};
const monitor = useAzureMonitor(options);
console.log("Azure Monitor initialized (offline storage configured)");
}
}
若要停用此功能,您應該設定 disableOfflineStorage = true。
根據預設,Azure 監視器匯出工具會使用下列路徑:
<tempfile.gettempdir()>/Microsoft/AzureMonitor/opentelemetry-python-<your-instrumentation-key>
若要覆寫預設目錄,您應將 storage_directory 設為您想要的目錄。
例如:
...
# Configure OpenTelemetry to use Azure Monitor with the specified connection string and storage directory.
# Replace `<YOUR-CONNECTION-STRING>` with the connection string to your Azure Monitor Application Insights resource.
# Replace `C:\\SomeDirectory` with the directory where you want to store the telemetry data before it is sent to Azure Monitor.
configure_azure_monitor(
connection_string="<YOUR-CONNECTION-STRING>",
storage_directory="C:\\SomeDirectory",
)
...
若要停用此功能,您應將 disable_offline_storage 設為 True。 預設為 False。
例如:
...
# Configure OpenTelemetry to use Azure Monitor with the specified connection string and disable offline storage.
# Replace `<YOUR-CONNECTION-STRING>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<YOUR-CONNECTION-STRING>",
disable_offline_storage=True,
)
...
啟用 OTLP 匯出工具
您可以讓 OpenTelemetry 通訊協定 (OTLP) 匯出工具與 Azure 監視器匯出工具一起將遙測傳送至兩個位置。
附註
OTLP 匯出工具的顯示只是為了方便起見。 我們不正式支援 OTLP 匯出工具及其下游的任何組件或第三方體驗。
在您的專案中安裝 OpenTelemetry.Exporter.OpenTelemetryProtocol 套件。
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
新增下列程式碼片段。 此範例假設您的 OpenTelemetry 收集器正在執行 OTLP 接收器。 如需詳細資訊,請參閱 GitHub 上的範例。
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Add the OpenTelemetry OTLP exporter to the application.
// This exporter will send telemetry data to an OTLP receiver, such as Prometheus
builder.Services.AddOpenTelemetry().WithTracing(builder => builder.AddOtlpExporter());
builder.Services.AddOpenTelemetry().WithMetrics(builder => builder.AddOtlpExporter());
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
在您的專案中安裝 OpenTelemetry.Exporter.OpenTelemetryProtocol 套件。
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
新增下列程式碼片段。 此範例假設您的 OpenTelemetry 收集器正在執行 OTLP 接收器。 如需詳細資訊,請參閱 GitHub 上的範例。
// Create a new OpenTelemetry tracer provider and add the Azure Monitor trace exporter and the OTLP trace exporter.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter()
.AddOtlpExporter()
.Build();
// Create a new OpenTelemetry meter provider and add the Azure Monitor metric exporter and the OTLP metric exporter.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddAzureMonitorMetricExporter()
.AddOtlpExporter()
.Build();
Application Insights Java 代理程式不支援 OTLP。
如需支援組態的詳細資訊,請參閱 Java 補充檔。
您無法讓 OpenTelemetry 通訊協定 (OTLP) 匯出工具與 Azure 監視器匯出工具一起將遙測傳送至兩個位置。
在專案中安裝 OpenTelemetry 收集器追蹤匯出 工具和其他 OpenTelemetry 套件。
npm install @opentelemetry/api
npm install @opentelemetry/exporter-trace-otlp-http
npm install @opentelemetry/sdk-trace-base
npm install @opentelemetry/sdk-trace-node
新增下列程式碼片段。 此範例假設您的 OpenTelemetry 收集器正在執行 OTLP 接收器。 如需詳細資訊,請參閱 GitHub 上的範例。
export class OtlpExporterSample {
static async run() {
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { BatchSpanProcessor } = await import("@opentelemetry/sdk-trace-base");
const { OTLPTraceExporter } = await import("@opentelemetry/exporter-trace-otlp-http");
// Create an OTLP trace exporter (set 'url' if your collector isn't on the default endpoint).
const otlpExporter = new OTLPTraceExporter({
// url: "http://localhost:4318/v1/traces",
});
// Configure Azure Monitor and add the OTLP exporter as an additional span processor.
const options = {
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<YOUR-CONNECTION-STRING>",
},
spanProcessors: [new BatchSpanProcessor(otlpExporter)],
};
const monitor = useAzureMonitor(options);
console.log("Azure Monitor initialized (OTLP exporter added)");
}
}
安裝 opentelemetry-exporter-otlp 套件。
新增下列程式碼片段。 此範例假設您的 OpenTelemetry 收集器正在執行 OTLP 接收器。 如需詳細資訊,請參閱此 自述檔。
# Import the `configure_azure_monitor()`, `trace`, `OTLPSpanExporter`, and `BatchSpanProcessor` classes from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace.export import BatchSpanProcessor
# 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 the tracer for the current module.
tracer = trace.get_tracer(__name__)
# Create an OTLP span exporter that sends spans to the specified endpoint.
# Replace `http://localhost:4317` with the endpoint of your OTLP collector.
otlp_exporter = OTLPSpanExporter(endpoint="http://localhost:4317")
# Create a batch span processor that uses the OTLP span exporter.
span_processor = BatchSpanProcessor(otlp_exporter)
# Add the batch span processor to the tracer provider.
trace.get_tracer_provider().add_span_processor(span_processor)
# Start a new span with the name "test".
with tracer.start_as_current_span("test"):
print("Hello world!")
OpenTelemetry 設定
使用 Azure 監視器 OpenTelemetry 散發版本時,可以透過環境變數存取下列 OpenTelemetry 組態。
| 環境變數 |
描述 |
APPLICATIONINSIGHTS_CONNECTION_STRING |
針對您的 Application Insights 資源將其設定為連接字串。 |
APPLICATIONINSIGHTS_STATSBEAT_DISABLED |
將其設定為 true 以退出內部計量收集。 |
OTEL_RESOURCE_ATTRIBUTES |
要用作資源屬性的索引鍵/值組。 如需資源屬性的詳細資訊,請參閱 資源 SDK 規格。 |
OTEL_SERVICE_NAME |
設定 service.name 資源屬性的值。 如果在 service.name 中也提供 OTEL_RESOURCE_ATTRIBUTES,則會優先使用 OTEL_SERVICE_NAME。 |
| 環境變數 |
描述 |
APPLICATIONINSIGHTS_CONNECTION_STRING |
針對您的 Application Insights 資源將其設定為連接字串。 |
APPLICATIONINSIGHTS_STATSBEAT_DISABLED |
將其設定為 true 以退出內部計量收集。 |
OTEL_RESOURCE_ATTRIBUTES |
要用作資源屬性的索引鍵/值組。 如需資源屬性的詳細資訊,請參閱 資源 SDK 規格。 |
OTEL_SERVICE_NAME |
設定 service.name 資源屬性的值。 如果在 service.name 中也提供 OTEL_RESOURCE_ATTRIBUTES,則會優先使用 OTEL_SERVICE_NAME。 |
修訂 URL 查詢字串
若要修訂 URL 查詢字串,請關閉查詢字串集合。 如果您使用 SAS 令牌呼叫 Azure 記憶體,建議您使用此設定。
當您使用 Azure.Monitor.OpenTelemetry.AspNetCore 散發套件時,會同時包含 ASP.NET Core 和 HttpClient 檢測程式庫。
我們的散發套件預設會將查詢字串修訂設定為關閉。
若要變更此行為,您必須將環境變數設定為 true 或 false。
ASP.NET 核心檢測:預設會停用 OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION 查詢字串修訂。 若要啟用,請將此環境變數設定為 false。
Http 用戶端檢測:預設會停用 OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION 查詢字串修訂。 若要啟用,請將此環境變數設定為 false。
使用 Azure.Monitor.OpenTelemetry.匯出器 時,您必須在 OpenTelemetry 設定中手動包含 ASP.NET Core 或 HttpClient Instrumentation 庫。
這些檢測程式庫預設會啟用查詢字串修訂。
若要變更此行為,您必須將環境變數設定為 true 或 false。
ASP.NET Core Instrumentation: OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION 預設會啟用查詢字串修訂。 若要停用,請將此環境變數設定為 true。
Http 用戶端檢測:預設會啟用 OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION 查詢字串修訂。 若要停用,請將此環境變數設定為 true。
將下列內容新增至 applicationinsights.json 組態檔:
{
"preview": {
"processors": [
{
"type": "attribute",
"actions": [
{
"key": "url.query",
"pattern": "^.*$",
"replace": "REDACTED",
"action": "mask"
}
]
},
{
"type": "attribute",
"actions": [
{
"key": "url.full",
"pattern": "[?].*$",
"replace": "?REDACTED",
"action": "mask"
}
]
}
]
}
}
我們正積極在 OpenTelemetry 社群中推動對修訂功能的支援。
當您使用 Azure 監視器 OpenTelemetry 散發套件時,可以透過建立範圍處理器並將其套用至散發組態來修訂查詢字串。
export class RedactQueryStringsSample {
static async run() {
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET, SEMATTRS_HTTP_URL } =
await import("@opentelemetry/semantic-conventions");
class RedactQueryStringProcessor {
forceFlush() { return Promise.resolve(); }
onStart() {}
shutdown() { return Promise.resolve(); }
onEnd(span: any) {
const route = String(span.attributes[SEMATTRS_HTTP_ROUTE] ?? "");
const url = String(span.attributes[SEMATTRS_HTTP_URL] ?? "");
const target = String(span.attributes[SEMATTRS_HTTP_TARGET] ?? "");
const strip = (s: string) => {
const i = s.indexOf("?");
return i === -1 ? s : s.substring(0, i);
};
if (route) span.attributes[SEMATTRS_HTTP_ROUTE] = strip(route);
if (url) span.attributes[SEMATTRS_HTTP_URL] = strip(url);
if (target) span.attributes[SEMATTRS_HTTP_TARGET] = strip(target);
}
}
const options = {
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<YOUR-CONNECTION-STRING>",
},
spanProcessors: [new RedactQueryStringProcessor()],
};
const monitor = useAzureMonitor(options);
console.log("Azure Monitor initialized (query strings redacted)");
}
}
我們正積極在 OpenTelemetry 社群中推動對修訂功能的支援。
計量匯出間隔
您可以使用環境變數來設定計量匯出間隔 OTEL_METRIC_EXPORT_INTERVAL 。
OTEL_METRIC_EXPORT_INTERVAL=60000
預設值為 60000 毫秒(60 秒)。 此設定可控制 OpenTelemetry SDK 匯出計量的頻率。
秘訣
Azure 監視器計量和 Azure 監視器工作區會以固定的 60 秒間隔內嵌自定義計量。 被更頻繁傳送的計量會每隔 60 秒緩衝並處理一次。 Log Analytics 會以傳送的間隔記錄計量,這可能會以較短的間隔增加成本,並以較長的間隔延遲可見度。
如需參考,請參閱下列 OpenTelemetry 規格: