配置 Azure Monitor OpenTelemetry
- 项目
本文介绍 Azure Monitor OpenTelemetry 发行版的配置设置。
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>" } }
备注
如果在多个位置设置连接字符串,我们遵循以下优先顺序:
- 代码
- 环境变量
- 配置文件
使用以下两种方法来配置连接字符串:
在应用程序启动时,将 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>
备注
如果在多个位置设置连接字符串,我们遵循以下优先顺序:
- 代码
- 环境变量
要设置连接字符串,请参阅连接字符串。
使用以下两种方法来配置连接字符串:
设置环境变量。
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
设置属性。
applicationinsights.connection.string=<Your Connection String>
使用以下两种方法来配置连接字符串:
设置环境变量。
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
使用配置对象。
// Import the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions class from the @azure/monitor-opentelemetry package. const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry"); // Create a new AzureMonitorOpenTelemetryOptions object. const options: AzureMonitorOpenTelemetryOptions = { azureMonitorExporterOptions: { connectionString: "<your connection string>" } }; // Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object. useAzureMonitor(options);
使用以下两种方法来配置连接字符串:
设置环境变量。
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.namespace
,它将回滚到 service.name
。 云角色实例使用 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(_testResourceAttributes));
// 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.namespace
,它将回滚到 service.name
。 云角色实例使用 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 原生映像应用程序
通过资源属性设置云角色名称和云角色实例。 云角色名称使用 service.namespace
和 service.name
属性,但如果未设置 service.namespace
,它将回滚到 service.name
。 云角色实例使用 service.instance.id
属性值。 有关资源的标准属性的信息,请参阅 OpenTelemetry 语义约定。
// Import the useAzureMonitor function, the AzureMonitorOpenTelemetryOptions class, the Resource class, and the SemanticResourceAttributes class from the @azure/monitor-opentelemetry, @opentelemetry/resources, and @opentelemetry/semantic-conventions packages, respectively.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
const { Resource } = require("@opentelemetry/resources");
const { SemanticResourceAttributes } = require("@opentelemetry/semantic-conventions");
// Create a new Resource object with the following custom resource attributes:
//
// * service_name: my-service
// * service_namespace: my-namespace
// * service_instance_id: my-instance
const customResource = new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: "my-service",
[SemanticResourceAttributes.SERVICE_NAMESPACE]: "my-namespace",
[SemanticResourceAttributes.SERVICE_INSTANCE_ID]: "my-instance",
});
// Create a new AzureMonitorOpenTelemetryOptions object and set the resource property to the customResource object.
const options: AzureMonitorOpenTelemetryOptions = {
resource: customResource
};
// Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object.
useAzureMonitor(options);
通过资源属性设置云角色名称和云角色实例。 云角色名称使用 service.namespace
和 service.name
属性,但如果未设置 service.namespace
,它将回滚到 service.name
。 云角色实例使用 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 提供自定义固定速率采样器,该采样器使用采样率填充事件,Application Insights 会将其转换为 ItemCount
。 固定速率采样器可确保准确的体验和事件计数。 采样器旨在跨服务保留跟踪,并可与较旧的 Application Insights 软件开发工具包 (SDK) 互操作。 有关详细信息,请参阅详细了解采样。
备注
指标和日志不受采样影响。
采样器需要 0 到 1 之间(含)的采样率。 0.1 意味着会发送大约 10% 的跟踪。
// 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 sampling ratio to 10%. This means that 10% of all traces will be sampled and sent to Azure Monitor.
options.SamplingRatio = 0.1F;
});
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
采样器需要 0 到 1 之间(含)的采样率。 0.1 意味着会发送大约 10% 的跟踪。
// 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 =>
{
// Set the sampling ratio to 10%. This means that 10% of all traces will be sampled and sent to Azure Monitor.
options.SamplingRatio = 0.1F;
})
.Build();
自 3.4.0 起开始提供速率限制采样,现在为默认设置。 有关采样的详细信息,请参阅 Java 采样。
对于 Spring Boot 原生应用程序,OpenTelemetry Java SDK 的抽样配置适用。
有关 Quarkus 原生应用程序,请查看 Quarkus OpenTelemetry 文档。
采样器需要 0 到 1 之间(含)的采样率。 0.1 意味着会发送大约 10% 的跟踪。
// Import the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions class from the @azure/monitor-opentelemetry package.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
// Create a new AzureMonitorOpenTelemetryOptions object and set the samplingRatio property to 0.1.
const options: AzureMonitorOpenTelemetryOptions = {
samplingRatio: 0.1
};
// Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object.
useAzureMonitor(options);
configure_azure_monitor()
函数会自动利用 ApplicationInsightsSampler 与 Application Insights SDK 的兼容,并对遥测数据进行采样。 OTEL_TRACES_SAMPLER_ARG
环境变量可用于指定采样率,有效范围为 0 到 1,其中 0 代表 0%,1 代表 100%。
例如,值 0.1 表示会发送 10% 的跟踪。
export OTEL_TRACES_SAMPLER_ARG=0.1
提示
使用固定比率/百分比采样时,如果你不确定如何设置采样率,请从 5%(即 0.05 采样率)开始,并根据失败和性能窗格中显示的操作准确度调整比率。 通常情况下,采样率越高,准确度越高。 但是,任何采样都会影响准确度,因此我们建议对不受采样影响的 OpenTelemetry 指标发出警报。
实时指标提供实时分析仪表板,用于深入了解应用程序活动和性能。
重要
有关 beta 版本、预览版或尚未正式发布的版本的 Azure 功能所适用的法律条款,请参阅 Azure 预览版的补充使用条款。
此功能默认启用。
配置发行版时,用户可以禁用实时指标。
builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
// Disable the Live Metrics feature.
options.EnableLiveMetrics = false;
});
此功能在 Azure Monitor .NET 导出程序中不可用。
备注
我们建议对控制台和辅助角色服务应用程序使用 Azure Monitor OpenTelemetry Exporter,它不包含实时指标。
默认情况下会启用实时指标体验。
有关 Java 配置的详细信息,请参阅配置选项:Azure Monitor Application Insights for Java。
实时指标目前不适用于 GraalVM 原生应用程序。
重要
有关 beta 版本、预览版或尚未正式发布的版本的 Azure 功能所适用的法律条款,请参阅 Microsoft Azure 预览版的补充使用条款。
使用 enableLiveMetrics
属性配置发行版时,用户可以启用/禁用实时指标。
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString:
process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
},
enableLiveMetrics: false
};
useAzureMonitor(options);
重要
有关 beta 版本、预览版或尚未正式发布的版本的 Azure 功能所适用的法律条款,请参阅 Microsoft Azure 预览版的补充使用条款。
可以使用适用于 Python 的 Azure Monitor OpenTelemetry 发行版启用实时指标,如下所示:
...
configure_azure_monitor(
enable_live_metrics=True
)
...
你可能需要启用 Microsoft Entra 身份验证,以便更安全地连接到 Azure,从而防止未经授权的遥测数据引入你的订阅。
我们支持 Azure 标识提供的凭据类。
- 建议使用
DefaultAzureCredential
进行本地开发。 - 建议使用
ManagedIdentityCredential
处理系统分配和用户分配的托管标识。- 对于系统分配的托管标识,使用不带参数的默认构造函数。
- 对于用户分配的托管标识,请向构造函数提供客户端 ID。
- 建议使用
ClientSecretCredential
处理服务主体。- 向构造函数提供租户 ID、客户端 ID 和客户端密码。
安装最新的 Azure.Identity 包:
dotnet add package Azure.Identity
提供所需的凭据类:
// 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 credential to the DefaultAzureCredential. // This credential will use the Azure identity of the current user or // the service principal that the application is running as to authenticate // to Azure Monitor. options.Credential = new DefaultAzureCredential(); }); // Build the ASP.NET Core web application. var app = builder.Build(); // Start the ASP.NET Core web application. app.Run();
我们支持 Azure 标识提供的凭据类。
- 建议使用
DefaultAzureCredential
进行本地开发。 - 建议使用
ManagedIdentityCredential
处理系统分配和用户分配的托管标识。- 对于系统分配的托管标识,使用不带参数的默认构造函数。
- 对于用户分配的托管标识,请向构造函数提供客户端 ID。
- 建议使用
ClientSecretCredential
处理服务主体。- 向构造函数提供租户 ID、客户端 ID 和客户端密码。
安装最新的 Azure.Identity 包:
dotnet add package Azure.Identity
提供所需的凭据类:
// Create a DefaultAzureCredential. var credential = new DefaultAzureCredential(); // Create a new OpenTelemetry tracer provider and set the credential. // It is important to keep the TracerProvider instance active throughout the process lifetime. var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAzureMonitorTraceExporter(options => { options.Credential = credential; }) .Build(); // Create a new OpenTelemetry meter provider and set the credential. // It is important to keep the MetricsProvider instance active throughout the process lifetime. var metricsProvider = Sdk.CreateMeterProviderBuilder() .AddAzureMonitorMetricExporter(options => { options.Credential = credential; }) .Build(); // Create a new logger factory and add the OpenTelemetry logger provider with the credential. // 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.Credential = credential; }); }); });
有关 Java 的详细信息,请参阅 Java 补充文档。
Microsoft Entra ID 身份验证不适用于 GraalVM 原生应用程序。
我们支持 Azure 标识提供的凭据类。
// Import the useAzureMonitor function, the AzureMonitorOpenTelemetryOptions class, and the ManagedIdentityCredential class from the @azure/monitor-opentelemetry and @azure/identity packages, respectively.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
const { ManagedIdentityCredential } = require("@azure/identity");
// Create a new ManagedIdentityCredential object.
const credential = new ManagedIdentityCredential();
// Create a new AzureMonitorOpenTelemetryOptions object and set the credential property to the credential object.
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString:
process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
credential: credential
}
};
// Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object.
useAzureMonitor(options);
用于 Python 的 Azure Monitor OpenTelemetry 发行版支持 Azure 标识提供的凭据类。
- 建议使用
DefaultAzureCredential
进行本地开发。 - 建议使用
ManagedIdentityCredential
处理系统分配和用户分配的托管标识。- 对于系统分配的托管标识,使用不带参数的默认构造函数。
- 对于用户分配的托管标识,向构造函数提供
client_id
。
- 建议使用
ClientSecretCredential
处理服务主体。- 向构造函数提供租户 ID、客户端 ID 和客户端密码。
如果使用 ManagedIdentityCredential
# Import the `ManagedIdentityCredential` class from the `azure.identity` package.
from azure.identity import ManagedIdentityCredential
# Import the `configure_azure_monitor()` function from the `azure.monitor.opentelemetry` package.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Configure the Distro to authenticate with Azure Monitor using a managed identity credential.
credential = ManagedIdentityCredential(client_id="<client_id>")
configure_azure_monitor(
connection_string="your-connection-string",
credential=credential,
)
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("hello with aad managed identity"):
print("Hello, World!")
如果使用 ClientSecretCredential
# Import the `ClientSecretCredential` class from the `azure.identity` package.
from azure.identity import ClientSecretCredential
# Import the `configure_azure_monitor()` function from the `azure.monitor.opentelemetry` package.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Configure the Distro to authenticate with Azure Monitor using a client secret credential.
credential = ClientSecretCredential(
tenant_id="<tenant_id",
client_id="<client_id>",
client_secret="<client_secret>",
)
configure_azure_monitor(
connection_string="your-connection-string",
credential=credential,
)
with tracer.start_as_current_span("hello with aad client secret identity"):
print("Hello, World!")
为了提高可靠性和复原能力,基于 OpenTelemetry 的 Azure Monitor 产品/服务默认在应用程序与 Application Insights 失去连接时写入脱机/本地存储。 这会将应用程序遥测数据保存到磁盘,并定期尝试再次发送遥测数据,最长持续时间为 48 小时。 在高负载应用程序中,遥测偶尔会出于两个原因而被删除。 首先,当允许的时间超过时;其次,当文件大小超过最大值或 SDK 没有机会清除文件时。 如果需要选择,产品会保存较新的事件,而不是较旧的事件。 了解详细信息
发行版包中包括 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 cannot 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 cannot 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 cannot 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 cannot be sent to Azure Monitor immediately.
options.StorageDirectory = "C:\\SomeDirectory";
});
});
});
若要禁用此功能,应设置 AzureMonitorExporterOptions.DisableOfflineStorage = true
。
在 Java 中无法配置脱机存储和自动重试。
有关可用配置的完整列表,请参阅配置选项。
在 Java 原生映像应用程序中无法配置脱机存储和自动重试。
默认情况下,AzureMonitorExporter 将使用以下位置之一进行脱机存储。
- Windows
- %TEMP%\Microsoft\AzureMonitor
- 非 Windows
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
若要替代默认目录,应设置 storageDirectory
。
例如:
// Import the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions class from the @azure/monitor-opentelemetry package.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
// Create a new AzureMonitorOpenTelemetryOptions object and set the azureMonitorExporterOptions property to an object with the following properties:
//
// * connectionString: The connection string for your Azure Monitor Application Insights resource.
// * storageDirectory: The directory where the Azure Monitor OpenTelemetry exporter will store telemetry data when it is offline.
// * disableOfflineStorage: A boolean value that specifies whether to disable offline storage.
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString: "<Your Connection String>",
storageDirectory: "C:\\SomeDirectory",
disableOfflineStorage: false
}
};
// Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object.
useAzureMonitor(options);
若要禁用此功能,应设置 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,
)
...
你可能想要启用 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();
有关 Java 的详细信息,请参阅 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 上的示例。
// Import the useAzureMonitor function, the AzureMonitorOpenTelemetryOptions class, the trace module, the ProxyTracerProvider class, the BatchSpanProcessor class, the NodeTracerProvider class, and the OTLPTraceExporter class from the @azure/monitor-opentelemetry, @opentelemetry/api, @opentelemetry/sdk-trace-base, @opentelemetry/sdk-trace-node, and @opentelemetry/exporter-trace-otlp-http packages, respectively. const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry"); const { BatchSpanProcessor } = require('@opentelemetry/sdk-trace-base'); const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http'); // Create a new OTLPTraceExporter object. const otlpExporter = new OTLPTraceExporter(); // Enable Azure Monitor integration. const options: AzureMonitorOpenTelemetryOptions = { // Add the SpanEnrichingProcessor spanProcessors: [new BatchSpanProcessor(otlpExporter)] } useAzureMonitor(options);
添加以下代码片段。 此示例假设你已经安装了一个 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!")
使用 Azure Monitor OpenTelemetry 发行版时,可以通过环境变量访问以下 OpenTelemetry 配置。
环境变量 | 说明 |
---|---|
APPLICATIONINSIGHTS_CONNECTION_STRING |
将其设置为 Application Insights 资源的连接字符串。 |
APPLICATIONINSIGHTS_STATSBEAT_DISABLED |
将其设置为 true 以选择退出内部指标收集。 |
OTEL_RESOURCE_ATTRIBUTES |
要用作资源属性的键值对。 有关资源属性的详细信息,请参阅资源 SDK 规范。 |
OTEL_SERVICE_NAME |
设置 service.name 资源属性的值。 如果 OTEL_RESOURCE_ATTRIBUTES 中也提供了 service.name ,则 OTEL_SERVICE_NAME 优先。 |
环境变量 | 说明 |
---|---|
APPLICATIONINSIGHTS_CONNECTION_STRING |
将其设置为 Application Insights 资源的连接字符串。 |
APPLICATIONINSIGHTS_STATSBEAT_DISABLED |
将其设置为 true 以选择退出内部指标收集。 |
OTEL_RESOURCE_ATTRIBUTES |
要用作资源属性的键值对。 有关资源属性的详细信息,请参阅资源 SDK 规范。 |
OTEL_SERVICE_NAME |
设置 service.name 资源属性的值。 如果 OTEL_RESOURCE_ATTRIBUTES 中也提供了 service.name ,则 OTEL_SERVICE_NAME 优先。 |
有关 Java 的详细信息,请参阅 Java 补充文档。
环境变量 | 说明 |
---|---|
APPLICATIONINSIGHTS_CONNECTION_STRING |
将其设置为 Application Insights 资源的连接字符串。 |
对于 Spring Boot 原生应用程序,OpenTelemetry Java SDK 配置可用。
有关 Quarkus 原生应用程序,请查看 Quarkus OpenTelemetry 文档。
有关 OpenTelemetry SDK 配置的详细信息,请参阅 OpenTelemetry 文档。
有关 OpenTelemetry SDK 配置的详细信息,请参阅 OpenTelemetry 文档和 Azure monitor 发行版使用情况。
若要编辑 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 发行版包时,可以通过创建范围处理器并将其应用到发行版配置来编辑查询字符串。
import { useAzureMonitor, AzureMonitorOpenTelemetryOptions } from "@azure/monitor-opentelemetry";
import { Context } from "@opentelemetry/api";
import { ReadableSpan, Span, SpanProcessor } from "@opentelemetry/sdk-trace-base";
import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET, SEMATTRS_HTTP_URL } from "@opentelemetry/semantic-conventions";
class RedactQueryStringProcessor implements SpanProcessor {
forceFlush(): Promise<void> {
return Promise.resolve();
}
onStart(span: Span, parentContext: Context): void {
return;
}
shutdown(): Promise<void> {
return Promise.resolve();
}
onEnd(span: ReadableSpan) {
const httpRouteIndex: number = String(span.attributes[SEMATTRS_HTTP_ROUTE]).indexOf('?');
const httpUrlIndex: number = String(span.attributes[SEMATTRS_HTTP_URL]).indexOf('?');
const httpTargetIndex: number = String(span.attributes[SEMATTRS_HTTP_TARGET]).indexOf('?');
if (httpRouteIndex !== -1) {
span.attributes[SEMATTRS_HTTP_ROUTE] = String(span.attributes[SEMATTRS_HTTP_ROUTE]).substring(0, httpRouteIndex);
}
if (httpUrlIndex !== -1) {
span.attributes[SEMATTRS_HTTP_URL] = String(span.attributes[SEMATTRS_HTTP_URL]).substring(0, httpUrlIndex);
}
if (httpTargetIndex !== -1) {
span.attributes[SEMATTRS_HTTP_TARGET] = String(span.attributes[SEMATTRS_HTTP_TARGET]).substring(0, httpTargetIndex);
}
}
}
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString: <YOUR_CONNECTION_STRING>,
},
spanProcessors: [new RedactQueryStringProcessor()]
};
useAzureMonitor(options);
我们正在 OpenTelemetry 社区中积极工作以支持编辑。