本指南介绍如何使用 Azure Monitor OpenTelemetry 发行版在 Azure Monitor 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 Monitor 导出器添加到每个 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 Monitor OpenTelemetry 发行版会自动检测资源上下文,并为组件的云角色名称和云角色实例属性提供默认值。 但是,可能需要将默认值替代为对团队有意义的值。 云角色名称值以节点下面的名称出现在应用程序映射上。
通过资源属性设置云角色名称和云角色实例。 云角色名称使用 service.namespace 和 service.name 属性,但如果未设置 service.name,它将回滚到 service.namespace。 云角色实例使用 service.instance.id 属性值。 有关资源的标准属性的信息,请参阅 OpenTelemetry 语义约定。
// 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 语义约定。
// 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 语义约定。
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 语义约定。
使用 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 追踪/秒)
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,
)
实时指标
实时指标提供实时分析仪表板,用于深入了解应用程序活动和性能。
此功能默认启用。
配置发行版时,用户可以禁用实时指标。
builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
// Disable the Live Metrics feature.
options.EnableLiveMetrics = false;
});
此功能在 Azure Monitor .NET 导出程序中不可用。
实时指标目前不适用于 GraalVM 原生应用程序。
使用 enableLiveMetrics 属性配置发行版时,用户可以启用/禁用实时指标。
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 Monitor OpenTelemetry 发行版启用实时指标,如下所示:
...
configure_azure_monitor(
enable_live_metrics=True
)
...
你可能需要启用 Microsoft Entra 身份验证,以便更安全地连接到 Azure,从而防止未经授权的遥测数据引入你的订阅。
有关详细信息,请参阅我们每种受支持的语言链接的专用Microsoft Entra 身份验证页。
Microsoft Entra ID 身份验证不适用于 GraalVM 原生应用程序。
脱机存储和自动重试
当应用程序与 Application Insights 断开连接并重试发送长达 48 小时时,基于 Azure Monitor OpenTelemetry 的产品/服务会缓存遥测数据。 有关数据处理建议,请参阅 导出和删除专用数据。 由于两个原因,高负载应用程序偶尔会删除遥测:超过允许的时间或超过最大文件大小。 如有必要,产品将最近事件优先于旧事件。
发行版包中包括 AzureMonitorExporter,默认情况下,它使用以下位置之一进行脱机存储(按优先顺序列出):
Windows操作系统
- %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 将使用以下位置之一进行脱机存储(按优先级顺序列出):
Windows操作系统
- %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 Monitor 时,它会将遥测文件存储在磁盘上。 这些文件保存在 telemetry 系统属性指定的 java.io.tmpdir 目录下的文件夹中。 每个文件名以时间戳开头,以扩展名结尾 .trn 。 这种脱机存储机制有助于确保在临时网络中断或引入失败期间保留遥测数据。
默认情况下,代理最多存储 50 MB 的遥测数据,并允许 配置存储限制。 定期尝试发送存储的遥测数据。 删除超过 48 小时的遥测文件,达到存储限制时会丢弃最早的事件。
有关可用配置的完整列表,请参阅配置选项。
当代理无法将遥测数据发送到 Azure Monitor 时,它会将遥测文件存储在磁盘上。 这些文件保存在 telemetry 系统属性指定的 java.io.tmpdir 目录下的文件夹中。 每个文件名以时间戳开头,以扩展名结尾 .trn 。 这种脱机存储机制有助于确保在临时网络中断或引入失败期间保留遥测数据。
默认情况下,代理最多存储 50 MB 的遥测数据。 定期尝试发送存储的遥测数据。 删除超过 48 小时的遥测文件,达到存储限制时会丢弃最早的事件。
默认情况下,AzureMonitorExporter 将使用以下位置之一进行脱机存储。
Windows操作系统
- %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 Monitor 导出程序使用以下路径:
<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 Monitor 导出器,以将遥测数据发送到两个位置。
注意
为方便起见,只展示了 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 Monitor 导出器来将遥测数据发送到两个位置。
在项目中安装 OpenTelemetry Collector Trace Exporter 和其他 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 Monitor OpenTelemetry Distros 时,可以通过环境变量访问以下 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 Core 检测:默认已禁用 OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION 查询字符串编修。 若要启用,请将此环境变量设置为 false。
Http 客户端检测:默认已禁用 OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION 查询字符串编修。 若要启用,请将此环境变量设置为 false。
使用 Azure.Monitor.OpenTelemetry.Exporter 时,必须手动将 ASP.NET Core 或 HttpClient 检测库包含在 OpenTelemetry 配置中。
默认情况下,这些仪器库已启用“查询字符串去除功能”。
若要更改此行为,必须将环境变量设置为 true 或 false。
ASP.NET Core 检测:默认已启用 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 Monitor 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 Monitor 指标和 Azure Monitor 工作区以固定的 60 秒间隔引入自定义指标。 发送更频繁的指标会每隔 60 秒缓冲并处理一次。 Log Analytics 会按发送的时间间隔记录指标,这可能会在较短间隔时增加成本,并在较长间隔时延迟指标的可见性。
有关参考,请参阅以下 OpenTelemetry 规范: