En esta guía se explica cómo configurar OpenTelemetry (OTel) en Application Insights de Azure Monitor mediante la distribución OpenTelemetry de Azure Monitor. La configuración adecuada garantiza una recopilación de datos de telemetría coherente en aplicaciones de .NET, Java, Node.jsy Python, lo que permite una supervisión y diagnóstico más confiables.
Cadena de conexión
Una cadena de conexión en Application Insights define la ubicación de destino para enviar datos de telemetría.
Use una de las tres maneras siguientes para configurar la cadena de conexión:
Agregue UseAzureMonitor()
al archivo de 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();
Establezca una variable de entorno.
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
Agregue la siguiente sección al archivo de configuración appsettings.json
.
{
"AzureMonitor": {
"ConnectionString": "<Your Connection String>"
}
}
Nota:
Si estableces la cadena de conexión en más de un lugar, se sigue la siguiente precedencia:
- Código
- Variable de entorno
- Archivo de configuración
Use una de las dos maneras siguientes para configurar la cadena de conexión:
Agregue Azure Monitor Exporter a cada señal de OpenTelemetry en el inicio de la aplicación.
// 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>";
});
});
});
Establezca una variable de entorno.
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
Nota:
Si estableces la cadena de conexión en más de un lugar, se sigue la siguiente precedencia:
- Código
- Variable de entorno
Use una de las dos maneras siguientes para configurar la cadena de conexión:
Establezca una variable de entorno.
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
Establezca una propiedad.
applicationinsights.connection.string=<Your Connection String>
Use una de las dos maneras siguientes para configurar la cadena de conexión:
Establezca una variable de entorno.
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
Use un objeto de configuración.
// 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);
Use una de las dos maneras siguientes para configurar la cadena de conexión:
Establezca una variable de entorno.
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
Utilice la función 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>",
)
Establecer el nombre de rol en la nube y la instancia de rol en la nube
Para idiomas admitidos, la distribución OpenTelemetry de Azure Monitor detecta automáticamente el contexto de recursos y proporciona valores predeterminados para el Nombre de rol en la nube y las propiedades de instancia de rol en la nube del componente. Sin embargo, es posible que desee reemplazar los valores predeterminados por algo que tenga sentido para el equipo. El valor del nombre del rol en la nube aparece en el mapa de aplicaciones como el nombre debajo de un nodo.
Puede establecer el nombre y la instancia de rol en la nube mediante los atributos de Recurso. El nombre de rol en la nube usa los atributos service.namespace
y service.name
, aunque recurre a service.name
si no se establece service.namespace
. La instancia de rol en la nube utiliza el valor del atributo service.instance.id
. Para obtener información sobre los atributos estándar de recursos, consulte Convenciones semánticas de 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();
Puede establecer el nombre y la instancia de rol en la nube mediante los atributos de Recurso. El nombre de rol en la nube usa los atributos service.namespace
y service.name
, aunque recurre a service.name
si no se establece service.namespace
. La instancia de rol en la nube utiliza el valor del atributo service.instance.id
. Para obtener información sobre los atributos estándar de recursos, consulte Convenciones semánticas de 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();
});
});
Para establecer el nombre del rol de nube:
- Use el
spring.application.name
para aplicaciones de imágenes nativas de Spring Boot
- Use el
quarkus.application.name
para aplicaciones de imágenes nativas de Quarkus
Puede establecer el nombre y la instancia de rol en la nube mediante los atributos de Recurso. El nombre de rol en la nube usa los atributos service.namespace
y service.name
, aunque recurre a service.name
si no se establece service.namespace
. La instancia de rol en la nube utiliza el valor del atributo service.instance.id
. Para obtener información sobre los atributos estándar de recursos, consulte Convenciones semánticas de 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);
Puede establecer el nombre y la instancia de rol en la nube mediante los atributos de Recurso. El nombre de rol en la nube usa los atributos service.namespace
y service.name
, aunque recurre a service.name
si no se establece service.namespace
. La instancia de rol en la nube utiliza el valor del atributo service.instance.id
. Para obtener información sobre los atributos estándar de recursos, consulte Convenciones semánticas de OpenTelemetry.
Establezca los atributos de los recursos usando las variables de entorno OTEL_RESOURCE_ATTRIBUTES
y/o OTEL_SERVICE_NAME
. OTEL_RESOURCE_ATTRIBUTES
toma series de pares clave-valor separados por comas. Por ejemplo, para establecer el Nombre del rol en la nube en my-namespace.my-helloworld-service
y establecer la Instancia de rol en la nube en my-instance
, puede establecer OTEL_RESOURCE_ATTRIBUTES
y OTEL_SERVICE_NAME
como tal:
export OTEL_RESOURCE_ATTRIBUTES="service.namespace=my-namespace,service.instance.id=my-instance"
export OTEL_SERVICE_NAME="my-helloworld-service"
Si no establece el atributo de recurso service.namespace
, puede establecer de manera alternativa el Nombre del rol en la nube solo con la variable de entorno OTEL_SERVICE_NAME o el atributo de recurso service.name
. Por ejemplo, para establecer el Nombre del rol en la nube en my-helloworld-service
y establecer la Instancia de rol en la nube en my-instance
, puede establecer OTEL_RESOURCE_ATTRIBUTES
y OTEL_SERVICE_NAME
como tal:
export OTEL_RESOURCE_ATTRIBUTES="service.instance.id=my-instance"
export OTEL_SERVICE_NAME="my-helloworld-service"
Habilitación del muestreo
Es posible que quiera habilitar el muestreo para reducir el volumen de ingesta de datos, lo que reduce el coste. Azure Monitor proporciona un muestreador personalizado de frecuencia fija que puebla los eventos con una relación de muestreo, que Application Insights convierte en ItemCount
. El muestreo de frecuencia fija garantiza experiencias y recuentos de eventos precisos. El muestreador está diseñado para conservar tus rastros entre servicios y es interoperable con los kits de desarrollo de software (SDKs) más antiguos de Application Insights. Para más información, consulte Más información sobre el muestreo.
Nota:
Las métricas y los registros no se ven afectados por el muestreo.
Si ve cargos inesperados o costos elevados en Application Insights, esta guía puede ayudarle. Abarca causas comunes, como un gran volumen de telemetría, picos de ingesta de datos y muestreo mal configurado. Es especialmente útil si está solucionando problemas relacionados con los picos de costos, el volumen de telemetría, el muestreo no funciona, los límites de datos, la ingesta alta o la facturación inesperada. Para empezar, consulte Solución de problemas de ingesta de datos elevados en Application Insights.
El muestreador espera una frecuencia de muestreo de entre 0 y 1, inclusive. Una tasa de 0,1 significa que se envía aproximadamente el 10 % de los seguimientos.
// 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();
El muestreador espera una frecuencia de muestreo de entre 0 y 1, inclusive. Una tasa de 0,1 significa que se envía aproximadamente el 10 % de los seguimientos.
// 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();
A partir de la versión 3.4.0, el muestreo de velocidad limitada está disponible y ahora es el método predeterminado. Para más información sobre el muestreo, consulte Muestreo de Java.
El muestreador espera una frecuencia de muestreo de entre 0 y 1, inclusive. Una tasa de 0,1 significa que se envía aproximadamente el 10 % de los seguimientos.
// 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);
La función configure_azure_monitor()
usa automáticamente ApplicationInsightsSampler para la compatibilidad con los SDK de Application Insights y para muestrear la telemetría. La variable de entorno OTEL_TRACES_SAMPLER_ARG
puede usarse para especificar la frecuencia de muestreo, con un rango válido de 0 a 1, donde 0 es 0 % y 1 es 100 %.
Por ejemplo, un valor de 0,1 significa que se envía aproximadamente el 10 % de los seguimientos.
export OTEL_TRACES_SAMPLER_ARG=0.1
Sugerencia
Al usar el muestreo con tasa fija o porcentaje y no está seguro de qué establecer la tasa de muestreo, comience en el 5 %. (Proporción de muestreo de 0,05) Ajuste la velocidad en función de la precisión de las operaciones mostradas en los paneles de rendimiento y errores. Una tasa más alta suele dar como resultado una mayor precisión. Sin embargo, cualquier muestreo afecta a la precisión, por lo que se recomienda alertar sobre Métricas de OpenTelemetry, que no se ven afectadas por el muestreo.
Métricas en vivo
Métricas en directo proporciona un panel de análisis en tiempo real para obtener información sobre la actividad y el rendimiento de las aplicaciones.
Esta característica está habilitada de forma predeterminada.
Los usuarios pueden deshabilitar Métricas en Vivo al configurar la Distro.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
// Disable the Live Metrics feature.
options.EnableLiveMetrics = false;
});
Esta característica no está disponible en el exportador Azure Monitor .NET.
Live Metrics no está disponible actualmente para aplicaciones nativas de GraalVM.
Los usuarios pueden habilitar o deshabilitar Métricas en directo al configurar la distribución mediante la propiedad enableLiveMetrics
.
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString:
process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
},
enableLiveMetrics: false
};
useAzureMonitor(options);
Puede habilitar las métricas directas mediante la distribución OpenTelemetry de Azure Monitor para Python de la siguiente manera:
...
configure_azure_monitor(
enable_live_metrics=True
)
...
Es posible que quiera habilitar la autenticación de Microsoft Entra para una conexión más segura a Azure, lo que impide que se ingieran datos de telemetría no autorizados en la suscripción.
Para obtener más información, consulte nuestra página dedicada de autenticación de Microsoft Entra vinculada para cada idioma admitido.
La autenticación de Microsoft Entra ID no está disponible para las aplicaciones nativas de GraalVM.
Almacenamiento sin conexión y reintentos automáticos
Las ofertas basadas en OpenTelemetry de Azure Monitor almacenan datos de telemetría en caché cuando una aplicación se desconecta de Application Insights y vuelve a intentar enviar hasta 48 horas. Para obtener recomendaciones de control de datos, consulte Exportación y eliminación de datos privados. Las aplicaciones de alta carga ocasionalmente omiten la telemetría por dos motivos: exceder el tiempo máximo permitido o exceder el tamaño máximo de archivo. Cuando sea necesario, el producto da prioridad a los eventos recientes sobre los antiguos.
El paquete de la distribución incluye AzureMonitorExporter que, de manera predeterminada, usa una de las siguientes ubicaciones para el almacenamiento sin conexión (se muestra en orden de prioridad):
- Windows
- %LOCALAPPDATA%\Microsoft\AzureMonitor
- %TEMP%\Microsoft\AzureMonitor
- Distinta de Windows
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
- /tmp/Microsoft/AzureMonitor
Para invalidar el directorio predeterminado, debe establecer 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();
Para deshabilitar esta característica, debe establecer AzureMonitorOptions.DisableOfflineStorage = true
.
De manera predeterminada, AzureMonitorExporter usa una de las siguientes ubicaciones para el almacenamiento sin conexión (se muestra en orden de prioridad):
- Windows
- %LOCALAPPDATA%\Microsoft\AzureMonitor
- %TEMP%\Microsoft\AzureMonitor
- Distinta de Windows
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
- /tmp/Microsoft/AzureMonitor
Para invalidar el directorio predeterminado, debe establecer 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";
});
});
});
Para deshabilitar esta característica, debe establecer AzureMonitorExporterOptions.DisableOfflineStorage = true
.
Cuando el agente no puede enviar telemetría a Azure Monitor, almacena los archivos de telemetría en el disco. Los archivos se guardan en una telemetry
carpeta en el directorio especificado por la propiedad del java.io.tmpdir
sistema. Cada nombre de archivo comienza con una marca de tiempo y termina con la .trn
extensión . Este mecanismo de almacenamiento sin conexión ayuda a garantizar que la telemetría se conserva durante interrupciones de red temporales o errores de ingesta.
El agente almacena hasta 50 MB de datos de telemetría de forma predeterminada y permite la configuración del límite de almacenamiento. Los intentos de enviar telemetría almacenada se realizan periódicamente. Los archivos de telemetría anteriores a 48 horas se eliminan y los eventos más antiguos se descartan cuando se alcanza el límite de almacenamiento.
Para obtener una lista completa de las configuraciones disponibles, consulte Opciones de configuración.
Cuando el agente no puede enviar telemetría a Azure Monitor, almacena los archivos de telemetría en el disco. Los archivos se guardan en una telemetry
carpeta en el directorio especificado por la propiedad del java.io.tmpdir
sistema. Cada nombre de archivo comienza con una marca de tiempo y termina con la .trn
extensión . Este mecanismo de almacenamiento sin conexión ayuda a garantizar que la telemetría se conserva durante interrupciones de red temporales o errores de ingesta.
El agente almacena hasta 50 MB de datos de telemetría de forma predeterminada. Los intentos de enviar telemetría almacenada se realizan periódicamente. Los archivos de telemetría anteriores a 48 horas se eliminan y los eventos más antiguos se descartan cuando se alcanza el límite de almacenamiento.
De manera predeterminada, AzureMonitorExporter usa una de las siguientes ubicaciones para el almacenamiento sin conexión.
- Windows
- %TEMP%\Microsoft\AzureMonitor
- Distinta de Windows
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
Para invalidar el directorio predeterminado, debe establecer storageDirectory
.
Por ejemplo:
// 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);
Para deshabilitar esta característica, debe establecer disableOfflineStorage = true
.
De manera predeterminada, los exportadores de Azure Monitor usan la siguiente ruta de acceso:
<tempfile.gettempdir()>/Microsoft/AzureMonitor/opentelemetry-python-<your-instrumentation-key>
Para invalidar el directorio predeterminado, debe establecer storage_directory
en el directorio que desee.
Por ejemplo:
...
# 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",
)
...
Para deshabilitar esta característica, debe establecer disable_offline_storage
en True
. Su valor predeterminado es False
.
Por ejemplo:
...
# 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,
)
...
Habilitación del exportador de OTLP
Es posible que quiera habilitar el exportador de OpenTelemetry Protocol (OTLP) junto con Azure Monitor Exporter para enviar los datos de telemetría a dos ubicaciones.
Nota:
El exportador de OTLP solo se muestra por comodidad. De manera oficial, no proporcionamos soporte técnico con relación al exportador de OTLP ni componentes o experiencias de terceros de nivel inferior.
Instale el paquete OpenTelemetry.Exporter.OpenTelemetryProtocol en el proyecto.
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
Agregue el siguiente fragmento de código. En este ejemplo se da por hecho que tiene un recopilador de OpenTelemetry con un receptor de OTLP en ejecución. Para obtener más información, consulte el ejemplo en 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();
Instale el paquete OpenTelemetry.Exporter.OpenTelemetryProtocol en el proyecto.
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
Agregue el siguiente fragmento de código. En este ejemplo se da por hecho que tiene un recopilador de OpenTelemetry con un receptor de OTLP en ejecución. Para obtener más información, consulte el ejemplo en 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();
No puede habilitar el exportador de OpenTelemetry Protocol (OTLP) junto con Azure Monitor Exporter para enviar los datos de telemetría a dos ubicaciones.
Instale OpenTelemetry Collector Trace Exporter y otros paquetes de OpenTelemetry en el proyecto.
npm install @opentelemetry/api
npm install @opentelemetry/exporter-trace-otlp-http
npm install @opentelemetry/sdk-trace-base
npm install @opentelemetry/sdk-trace-node
Agregue el siguiente fragmento de código. En este ejemplo se da por hecho que tiene un recopilador de OpenTelemetry con un receptor de OTLP en ejecución. Para obtener más información, consulte el ejemplo en 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);
Instale el paquete opentelemetry-exporter-otlp.
Agregue el siguiente fragmento de código. En este ejemplo se da por hecho que tiene un recopilador de OpenTelemetry con un receptor de OTLP en ejecución. Para obtener más información, consulte este archivo README.
# 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!")
Configuración de OpenTelemetry
Se puede acceder a las siguientes configuraciones de OpenTelemetry a través de variables de entorno al usar las distribuciones de OpenTelemetry de Azure Monitor.
Variable de entorno |
Descripción |
APPLICATIONINSIGHTS_CONNECTION_STRING |
Establezca esto en la cadena de conexión del recurso de Application Insights. |
APPLICATIONINSIGHTS_STATSBEAT_DISABLED |
Establézcalo en true para no participar en la recopilación de métricas internas. |
OTEL_RESOURCE_ATTRIBUTES |
Pares clave-valor que se usarán como atributos de recursos. Para obtener más información sobre los atributos de recursos, consulte la especificación del SDK de recursos. |
OTEL_SERVICE_NAME |
Establece el valor del atributo de recurso service.name . Si service.name también se proporciona en OTEL_RESOURCE_ATTRIBUTES , OTEL_SERVICE_NAME tendrá prioridad. |
Variable de entorno |
Descripción |
APPLICATIONINSIGHTS_CONNECTION_STRING |
Establezca esto en la cadena de conexión del recurso de Application Insights. |
APPLICATIONINSIGHTS_STATSBEAT_DISABLED |
Establézcalo en true para no participar en la recopilación de métricas internas. |
OTEL_RESOURCE_ATTRIBUTES |
Pares clave-valor que se usarán como atributos de recursos. Para obtener más información sobre los atributos de recursos, consulte la especificación del SDK de recursos. |
OTEL_SERVICE_NAME |
Establece el valor del atributo de recurso service.name . Si service.name también se proporciona en OTEL_RESOURCE_ATTRIBUTES , OTEL_SERVICE_NAME tendrá prioridad. |
Redactar cadenas de consulta de URL
Para tachar las cadenas de consulta URL, desactive la recopilación de cadenas de consulta. Recomendamos esta configuración si realiza llamadas al almacenamiento de Azure usando un token SAS.
Al usar el paquete de distribución de Azure.Monitor.OpenTelemetry.AspNetCore, se incluyen las bibliotecas de ASP.NET Core y HttpClient Instrumentation.
Nuestro paquete de distribución establece la acción de tachar cadenas de consulta como desactivada de forma predeterminada.
Para cambiar este comportamiento, debe establecer una variable de entorno en true
o false
.
- Instrumentación de ASP.NET Core: la acción de tachar cadenas de consulta de
OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION
está deshabilitada de manera predeterminada. Para habilitar, establezca esta variable de entorno en false
.
- Instrumentación de cliente Http: la acción de tachar cadenas de consulta de
OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION
está deshabilitada de manera predeterminada. Para habilitar, establezca esta variable de entorno en false
.
Cuando utilice Azure.Monitor.OpenTelemetry.Exporter, deberá incluir manualmente las bibliotecas de Instrumentación deASP.NET Core o HttpClienten la configuración de OpenTelemetry.
Estas bibliotecas de instrumentación tienen la redacción de cadenas de consulta habilitada de forma predeterminada.
Para cambiar este comportamiento, debe establecer una variable de entorno en true
o false
.
- Instrumentación de ASP.NET Core: la acción de tachar cadenas de consulta de
OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION
está habilitada de manera predeterminada. Para deshabilitarlo, establezca esta variable de entorno en true
.
- Instrumentación de cliente Http: la acción de tachar cadenas de consulta de
OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION
está habilitada de manera predeterminada. Para deshabilitarlo, establezca esta variable de entorno en true
.
Agregue lo siguiente al archivo de configuración de 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"
}
]
}
]
}
}
Estamos trabajando activamente en la comunidad de OpenTelemetry para admitir la acción de tachar.
Al usar el paquete de distribución OpenTelemetry de Azure Monitor, las cadenas de consulta se pueden censurar mediante la creación y aplicación de un procesador de intervalos a la configuración de distribución.
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);
Estamos trabajando activamente en la comunidad de OpenTelemetry para admitir la acción de tachar.