Questa guida illustra come configurare OpenTelemetry (OTel) nel Monitoraggio di Azure Application Insights usando la distribuzione di OpenTelemetry di Monitoraggio di Azure. La configurazione corretta garantisce una raccolta coerente dei dati di telemetria tra applicazioni .NET, Java, Node.jse Python, consentendo un monitoraggio e una diagnostica più affidabili.
Stringa di connessione
Una stringa di connessione in Application Insights definisce la posizione di destinazione per l'invio dei dati di telemetria.
Adottare uno dei tre modi seguenti per configurare la stringa di connessione:
Aggiungere UseAzureMonitor()
al file 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();
Impostare una variabile di ambiente.
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
Aggiungere la sezione seguente al file di configurazione appsettings.json
.
{
"AzureMonitor": {
"ConnectionString": "<Your Connection String>"
}
}
Nota
Se si imposta la stringa di connessione in più posizioni, viene osservato l'ordine di precedenza seguente:
- Codice
- Variabile di ambiente
- File di configurazione
Adottare uno dei due modi seguenti per configurare la stringa di connessione:
All'avvio dell'applicazione, aggiungere l'utilità di esportazione di Monitoraggio di Azure a ogni segnale 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>";
});
});
});
Impostare una variabile di ambiente.
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
Nota
Se si imposta la stringa di connessione in più posizioni, viene osservato l'ordine di precedenza seguente:
- Codice
- Variabile di ambiente
Adottare uno dei due modi seguenti per configurare la stringa di connessione:
Impostare una variabile di ambiente.
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
Impostare una proprietà.
applicationinsights.connection.string=<Your Connection String>
Adottare uno dei due modi seguenti per configurare la stringa di connessione:
Impostare una variabile di ambiente.
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
Usare un oggetto di configurazione.
// 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);
Adottare uno dei due modi seguenti per configurare la stringa di connessione:
Impostare una variabile di ambiente.
APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
Usare la funzione 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>",
)
Impostare il nome e l'istanza del ruolo cloud
Per le lingue supportate, la distribuzione OpenTelemetry di Monitoraggio di Azure rileva automaticamente il contesto delle risorse e fornisce i valori predefiniti per le proprietà Nome ruolo cloud e Istanza del ruolo cloud del componente. È tuttavia possibile sostituire i valori predefiniti con altri più pertinenti per il proprio team. Nella mappa delle applicazioni, il valore del nome del ruolo cloud corrisponde al nome visualizzato sotto un nodo.
Imposta il Cloud Role Name e il Cloud Role Instance tramite gli attributi Resource. Il nome del ruolo cloud usa gli attributi service.namespace
e service.name
ma, se service.name
non è impostato, esegue il fallback a service.namespace
. L'istanza del ruolo cloud usa il valore di attributo service.instance.id
. Per informazioni sugli attributi standard per le risorse, vedere Convenzioni semantiche 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();
Imposta il Cloud Role Name e il Cloud Role Instance tramite gli attributi Resource. Il nome del ruolo cloud usa gli attributi service.namespace
e service.name
ma, se service.name
non è impostato, esegue il fallback a service.namespace
. L'istanza del ruolo cloud usa il valore di attributo service.instance.id
. Per informazioni sugli attributi standard per le risorse, vedere Convenzioni semantiche 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();
});
});
Per impostare il nome del ruolo cloud:
- Usare il valore
spring.application.name
per le applicazioni di immagini native Spring Boot
- Usare il valore
quarkus.application.name
per le applicazioni di immagini native Quarkus
Imposta il Cloud Role Name e il Cloud Role Instance tramite gli attributi Resource. Il nome del ruolo cloud usa gli attributi service.namespace
e service.name
ma, se service.name
non è impostato, esegue il fallback a service.namespace
. L'istanza del ruolo cloud usa il valore di attributo service.instance.id
. Per informazioni sugli attributi standard per le risorse, vedere Convenzioni semantiche 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);
Imposta il Cloud Role Name e il Cloud Role Instance tramite gli attributi Resource. Il nome del ruolo cloud usa gli attributi service.namespace
e service.name
ma, se service.name
non è impostato, esegue il fallback a service.namespace
. L'istanza del ruolo cloud usa il valore di attributo service.instance.id
. Per informazioni sugli attributi standard per le risorse, vedere Convenzioni semantiche OpenTelemetry.
Impostare gli attributi di risorsa usando le variabili di ambiente OTEL_RESOURCE_ATTRIBUTES
e/o OTEL_SERVICE_NAME
.
OTEL_RESOURCE_ATTRIBUTES
accetta serie di coppie chiave-valore separate da virgole. Per impostare il nome del ruolo cloud su my-namespace.my-helloworld-service
e l'istanza del ruolo cloud su my-instance
, ad esempio, è possibile impostare OTEL_RESOURCE_ATTRIBUTES
e OTEL_SERVICE_NAME
come segue:
export OTEL_RESOURCE_ATTRIBUTES="service.namespace=my-namespace,service.instance.id=my-instance"
export OTEL_SERVICE_NAME="my-helloworld-service"
Se l'attributo di risorsa service.namespace
non è impostato, è comunque possibile impostare il nome del ruolo cloud solo con la variabile di ambiente OTEL_SERVICE_NAME o con l'attributo di risorsa service.name
. Per impostare il nome del ruolo cloud su my-helloworld-service
e l'istanza del ruolo cloud su my-instance
, ad esempio, è possibile impostare OTEL_RESOURCE_ATTRIBUTES
e OTEL_SERVICE_NAME
come segue:
export OTEL_RESOURCE_ATTRIBUTES="service.instance.id=my-instance"
export OTEL_SERVICE_NAME="my-helloworld-service"
Abilitare il campionamento
Per ridurre il volume di inserimento dati, limitando quindi i costi, è possibile abilitare il campionamento. Azure Monitor fornisce un campionatore personalizzato a frequenza fissa che assegna un rapporto di campionamento agli eventi, che Application Insights converte in ItemCount
. Il campionatore a frequenza fissa garantisce esperienze accurate e conteggi di eventi. Il campionatore è progettato per mantenere le tracce sui servizi ed è interoperabile con i precedenti SDK (Software Development Kit) di Application Insights. Per altre informazioni, vedere Altre informazioni sul campionamento.
Nota
Le metriche e i log sono esclusi dal campionamento.
Se vengono visualizzati addebiti imprevisti o costi elevati in Application Insights, questa guida può essere utile. Vengono illustrate le cause comuni, ad esempio volumi di telemetria elevati, picchi di inserimento dati e campionamento non configurato correttamente. È particolarmente utile se si stanno risolvendo problemi relativi a picchi di costo, volume di telemetria, campionamento non funzionante, limiti di dati, inserimento elevato o fatturazione imprevista. Per iniziare, vedere Risolvere i problemi relativi all'inserimento dati elevato in Application Insights.
Il campionatore prevede una frequenza di campionamento compresa tra 0 e 1 (inclusi). Un tasso pari a 0,1 indica che viene inviato circa il 10% delle tracce.
// 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();
Il campionatore prevede una frequenza di campionamento compresa tra 0 e 1 (inclusi). Un tasso pari a 0,1 indica che viene inviato circa il 10% delle tracce.
// 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 partire dalla versione 3.4.0 è disponibile il campionamento con frequenza limitata, che costituisce ora il valore predefinito. Per altre informazioni sul campionamento, vedere Campionamento Java.
Il campionatore prevede una frequenza di campionamento compresa tra 0 e 1 (inclusi). Un tasso pari a 0,1 indica che viene inviato circa il 10% delle tracce.
// 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 funzione configure_azure_monitor()
usa automaticamente ApplicationInsightsSampler per la compatibilità con gli SDK di Application Insights e per il campionamento dei dati di telemetria. La variabile di ambiente OTEL_TRACES_SAMPLER_ARG
può essere usata per specificare la frequenza di campionamento, con un intervallo valido compreso tra 0 e 1, dove 0 corrisponde allo 0% e 1 al 100%.
Un valore pari a 0,1, ad esempio, indica che viene inviato circa il 10% delle tracce.
export OTEL_TRACES_SAMPLER_ARG=0.1
Suggerimento
Quando si usa il campionamento a velocità fissa/percentuale e non si è certi di cosa impostare la frequenza di campionamento, iniziare al 5%. (rapporto di campionamento 0,05) Modificare la frequenza in base all'accuratezza delle operazioni visualizzate nei riquadri errori e prestazioni. Una frequenza più elevata comporta in genere un'accuratezza maggiore. Tuttavia, il campionamento ANY influisce sull'accuratezza, pertanto è consigliabile inviare avvisi sulle metriche OpenTelemetry, che non sono interessate dal campionamento.
Metriche attive
Le metriche in tempo reale forniscono un dashboard di analisi in tempo reale per informazioni dettagliate sulle attività e sulle prestazioni dell'applicazione.
Questa funzionalità è abilitata per impostazione predefinita.
Gli utenti possono disabilitare le metriche in tempo reale durante la configurazione della distribuzione.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
// Disable the Live Metrics feature.
options.EnableLiveMetrics = false;
});
Questa funzionalità non è disponibile nell'utilità di esportazione .NET di Monitoraggio di Azure.
Le metriche attive non sono attualmente disponibili per le applicazioni native graalVM.
Gli utenti possono abilitare/disabilitare le metriche in tempo reale durante la configurazione della distribuzione usando la proprietà enableLiveMetrics
.
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString:
process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
},
enableLiveMetrics: false
};
useAzureMonitor(options);
È possibile abilitare le metriche in tempo reale usando la distribuzione OpenTelemetry di Monitoraggio di Azure per Python, come indicato di seguito:
...
configure_azure_monitor(
enable_live_metrics=True
)
...
Per una connessione più sicura ad Azure è possibile abilitare l'autenticazione di Microsoft Entra, che impedisce l'inserimento di dati di telemetria non autorizzati nella sottoscrizione.
Per altre informazioni, vedere la pagina dedicata relativa all'autenticazione di Microsoft Entra collegata per ogni lingua supportata.
L'autenticazione di Microsoft Entra ID non è disponibile per le applicazioni GraalVM Native.
Archiviazione offline e retry automatici
Le offerte basate su OpenTelemetry di Monitor di Azure memorizzano nella cache i dati di telemetria per un massimo di 48 ore, quando un'applicazione si disconnette da Application Insights e ritenta l'invio. Per le raccomandazioni sulla gestione dei dati, vedere Esportare ed eliminare dati privati. Le applicazioni ad alto carico rilasciano occasionalmente i dati di telemetria per due motivi: il superamento del tempo consentito o il superamento delle dimensioni massime del file. Quando necessario, il prodotto assegna priorità agli eventi recenti rispetto a quelli precedenti.
Il pacchetto di distribuzione include AzureMonitorExporter, che per impostazione predefinita usa uno dei percorsi seguenti per la risorsa di archiviazione offline (elencati in ordine di precedenza):
- Windows
- %LOCALAPPDATA%\Microsoft\AzureMonitor
- %TEMP%\Microsoft\AzureMonitor
- Non Windows
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
- /tmp/Microsoft/AzureMonitor
Per eseguire l'override della directory predefinita, impostare 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();
Per disabilitare questa funzionalità, impostare AzureMonitorOptions.DisableOfflineStorage = true
.
Per impostazione predefinita, AzureMonitorExporter usa uno dei percorsi seguenti per la risorsa di archiviazione offline (elencati in ordine di precedenza):
- Windows
- %LOCALAPPDATA%\Microsoft\AzureMonitor
- %TEMP%\Microsoft\AzureMonitor
- Non Windows
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
- /tmp/Microsoft/AzureMonitor
Per eseguire l'override della directory predefinita, impostare 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";
});
});
});
Per disabilitare questa funzionalità, impostare AzureMonitorExporterOptions.DisableOfflineStorage = true
.
Quando l'agente non può inviare dati di telemetria a Monitoraggio di Azure, archivia i file di telemetria su disco. I file vengono salvati in una telemetry
cartella nella directory specificata dalla proprietà di java.io.tmpdir
sistema. Ogni nome di file inizia con un timestamp e termina con l'estensione .trn
. Questo meccanismo di archiviazione offline consente di garantire che i dati di telemetria vengano conservati durante interruzioni temporanee della rete o errori di inserimento.
L'agente archivia fino a 50 MB di dati di telemetria per impostazione predefinita e consente la configurazione del limite di archiviazione. I tentativi di invio di dati di telemetria archiviati vengono eseguiti periodicamente. I file di telemetria precedenti a 48 ore vengono eliminati e gli eventi meno recenti vengono eliminati quando viene raggiunto il limite di archiviazione.
Per un elenco completo delle configurazioni disponibili, vedere Opzioni di configurazione.
Quando l'agente non può inviare dati di telemetria a Monitoraggio di Azure, archivia i file di telemetria su disco. I file vengono salvati in una telemetry
cartella nella directory specificata dalla proprietà di java.io.tmpdir
sistema. Ogni nome di file inizia con un timestamp e termina con l'estensione .trn
. Questo meccanismo di archiviazione offline consente di garantire che i dati di telemetria vengano conservati durante interruzioni temporanee della rete o errori di inserimento.
L'agente archivia fino a 50 MB di dati di telemetria per impostazione predefinita. I tentativi di invio di dati di telemetria archiviati vengono eseguiti periodicamente. I file di telemetria precedenti a 48 ore vengono eliminati e gli eventi meno recenti vengono eliminati quando viene raggiunto il limite di archiviazione.
Per impostazione predefinita, AzureMonitorExporter usa uno dei percorsi seguenti per la risorsa di archiviazione offline.
- Windows
- %TEMP%\Microsoft\AzureMonitor
- Non Windows
- %TMPDIR%/Microsoft/AzureMonitor
- /var/tmp/Microsoft/AzureMonitor
Per eseguire l'override della directory predefinita, impostare storageDirectory
.
Ad esempio:
// 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);
Per disabilitare questa funzionalità, impostare disableOfflineStorage = true
.
Per impostazione predefinita, le utilità di esportazione di Monitoraggio di Azure usano il percorso seguente:
<tempfile.gettempdir()>/Microsoft/AzureMonitor/opentelemetry-python-<your-instrumentation-key>
Per eseguire l'override della directory predefinita, impostare storage_directory
sulla directory desiderata.
Ad esempio:
...
# 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",
)
...
Per disabilitare questa funzionalità, impostare disable_offline_storage
su True
. Il valore predefinito è False
.
Ad esempio:
...
# 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,
)
...
Abilitare l'utilità di esportazione di OTLP
Per salvare i dati di telemetria su due percorsi diversi, è possibile abilitare l'utilità di esportazione OTLP (OpenTelemetry Protocol) contestualmente all'utilità di esportazione di Monitoraggio di Azure.
Nota
L'utilità di esportazione OTLP viene mostrata qui solo per praticità. Non viene infatti fornito il supporto ufficiale dell'utilità di esportazione OTLP, né di alcun componente o esperienza di terze parti a valle.
Installare il pacchetto OpenTelemetry.Exporter.OpenTelemetryProtocol nel progetto.
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
Aggiungere il frammento di codice seguente. In questo esempio si presuppone che sia presente un agente di raccolta OpenTelemetry con un ricevitore OTLP in esecuzione. Per informazioni dettagliate, vedere l'esempio in 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();
Installare il pacchetto OpenTelemetry.Exporter.OpenTelemetryProtocol nel progetto.
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
Aggiungere il frammento di codice seguente. In questo esempio si presuppone che sia presente un agente di raccolta OpenTelemetry con un ricevitore OTLP in esecuzione. Per informazioni dettagliate, vedere l'esempio in 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();
Non è possibile abilitare l'utilità di esportazione OTLP (OpenTelemetry Protocol) contestualmente all'utilità di esportazione di Monitoraggio di Azure per salvare i dati di telemetria su due percorsi diversi.
Installare OpenTelemetry Collector Trace Exporter e altri pacchetti OpenTelemetry nel progetto.
npm install @opentelemetry/api
npm install @opentelemetry/exporter-trace-otlp-http
npm install @opentelemetry/sdk-trace-base
npm install @opentelemetry/sdk-trace-node
Aggiungere il frammento di codice seguente. In questo esempio si presuppone che sia presente un agente di raccolta OpenTelemetry con un ricevitore OTLP in esecuzione. Per informazioni dettagliate, vedere l'esempio in 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);
Installare il pacchetto opentelemetry-exporter-otlp .
Aggiungere il frammento di codice seguente. In questo esempio si presuppone che sia presente un agente di raccolta OpenTelemetry con un ricevitore OTLP in esecuzione. Per informazioni dettagliate, vedere questo file 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!")
Configurazioni di OpenTelemetry
Per accedere alle configurazioni di OpenTelemetry seguenti, è necessario applicare specifiche variabili di ambiente durante l'uso delle distribuzioni OpenTelemetry di Monitoraggio di Azure.
Variabile di ambiente |
Descrizione |
APPLICATIONINSIGHTS_CONNECTION_STRING |
Impostarla sulla stringa di connessione per la risorsa di Application Insights. |
APPLICATIONINSIGHTS_STATSBEAT_DISABLED |
Impostarla su true per rifiutare esplicitamente la raccolta di metriche interne. |
OTEL_RESOURCE_ATTRIBUTES |
Coppie chiave-valore da usare come attributi di risorsa. Per altre informazioni sugli attributi delle risorse, vedere la specifica di Resource SDK. |
OTEL_SERVICE_NAME |
Impostare il valore dell'attributo di risorsa service.name . Se service.name viene specificato anche in OTEL_RESOURCE_ATTRIBUTES , viene assegnata la precedenza a OTEL_SERVICE_NAME . |
Variabile di ambiente |
Descrizione |
APPLICATIONINSIGHTS_CONNECTION_STRING |
Impostarla sulla stringa di connessione per la risorsa di Application Insights. |
APPLICATIONINSIGHTS_STATSBEAT_DISABLED |
Impostarla su true per rifiutare esplicitamente la raccolta di metriche interne. |
OTEL_RESOURCE_ATTRIBUTES |
Coppie chiave-valore da usare come attributi di risorsa. Per altre informazioni sugli attributi delle risorse, vedere la specifica di Resource SDK. |
OTEL_SERVICE_NAME |
Impostare il valore dell'attributo di risorsa service.name . Se service.name viene specificato anche in OTEL_RESOURCE_ATTRIBUTES , viene assegnata la precedenza a OTEL_SERVICE_NAME . |
Redigere stringhe di query URL
Per ridistribuire le stringhe di query URL, disattivare la raccolta di stringhe di query. È consigliabile usare questa impostazione se si chiama Archiviazione di Azure usando un token di firma di accesso condiviso.
Quando si usa il pacchetto di distribuzione Azure.Monitor.OpenTelemetry.AspNetCore , sono incluse entrambe le librerie di strumentazione Core e HttpClient ASP.NET.
Il pacchetto di distribuzione imposta la ridistribuzione della stringa di query disattivata per impostazione predefinita.
Per modificare questo comportamento, è necessario impostare una variabile di ambiente su true
o false
.
- ASP.NET Strumentazione principale:
OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION
la ridistribuzione della stringa di query è disabilitata per impostazione predefinita. Per abilitare, impostare questa variabile di ambiente su false
.
- Strumentazione client HTTP:
OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION
la ridistribuzione della stringa di query è disabilitata per impostazione predefinita. Per abilitare, impostare questa variabile di ambiente su false
.
Quando si usa Azure.Monitor.OpenTelemetry.Exporter, è necessario includere manualmente le librerie ASP.NET Core o HttpClient Instrumentation nella configurazione openTelemetry.
Per impostazione predefinita, queste librerie di strumentazione includono QueryString Redaction abilitato.
Per modificare questo comportamento, è necessario impostare una variabile di ambiente su true
o false
.
- ASP.NET Strumentazione principale:
OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION
la ridistribuzione della stringa di query è abilitata per impostazione predefinita. Per disabilitare, impostare questa variabile di ambiente su true
.
- Strumentazione client HTTP:
OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION
la ridistribuzione della stringa di query è abilitata per impostazione predefinita. Per disabilitare, impostare questa variabile di ambiente su true
.
Aggiungere quanto segue al applicationinsights.json
file di configurazione:
{
"preview": {
"processors": [
{
"type": "attribute",
"actions": [
{
"key": "url.query",
"pattern": "^.*$",
"replace": "REDACTED",
"action": "mask"
}
]
},
{
"type": "attribute",
"actions": [
{
"key": "url.full",
"pattern": "[?].*$",
"replace": "?REDACTED",
"action": "mask"
}
]
}
]
}
}
Stiamo lavorando attivamente alla community di OpenTelemetry per supportare l'approvazione.
Quando si usa il pacchetto di distribuzione OpenTelemetry di Monitoraggio di Azure, è possibile redigere stringhe di query tramite la creazione e l'applicazione di un processore span alla configurazione della distribuzione.
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);
Stiamo lavorando attivamente alla community di OpenTelemetry per supportare l'approvazione.