Le seguenti librerie di strumentazione OpenTelemetry sono incluse come parte della distribuzione di Application Insights di Monitoraggio di Azure. Per altre informazioni, vedere Azure SDK per JavaScript.
Alcuni esempi di uso della libreria di registrazione Python sono disponibili in GitHub.
I dati di telemetria generati dagli SDK Azure vengono raccolti automaticamente per impostazione predefinita.
Note
¹: supporta la creazione automatica di report relativi alle eccezioni non gestite/non rilevate
²: supporta le metriche OpenTelemetry
²: per impostazione predefinita, la registrazione viene raccolta solo a livello di INFO o superiore. Per modificare questa impostazione, vedere le opzioni di configurazione.
⁴: per impostazione predefinita, la registrazione viene raccolta solo quando la registrazione viene eseguita a livello di AVVISO o superiore.
Nota
Le distribuzioni OpenTelemetry di Monitoraggio di Azure includono mapping personalizzato e logica per generare automaticamente metriche standard di Application Insights.
Suggerimento
Tutte le metriche di OpenTelemetry raccolte automaticamente dalle librerie di strumentazione o raccolte manualmente dalla codifica personalizzata sono attualmente considerate "metriche personalizzate" di Application Insights ai fini della fatturazione. Altre informazioni.
Aggiungere una libreria di strumentazione della community
È possibile raccogliere più dati automaticamente quando si includono librerie di strumentazione della community OpenTelemetry.
Attenzione
Non è supportata né garantita la qualità delle librerie di strumentazione della community. Per suggerire una distribuzione, pubblicare o votare a favore nella community feedback. Tenere presente che alcune si basano sulle specifiche sperimentali OpenTelemetry e potrebbero introdurre modifiche di rilievo future.
Per aggiungere una libreria della community, usare i metodi ConfigureOpenTelemetryMeterProvider o ConfigureOpenTelemetryTracerProvider dopo aver aggiunto il pacchetto NuGet per la libreria.
L'esempio seguente illustra la modalità di aggiunta della Strumentazione runtime per raccogliere metriche aggiuntive:
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add runtime instrumentation.
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddRuntimeInstrumentation());
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
L'esempio seguente illustra la modalità di aggiunta della Strumentazione runtime per raccogliere metriche aggiuntive:
// Create a new OpenTelemetry meter provider and add runtime instrumentation and the Azure Monitor metric exporter.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddRuntimeInstrumentation()
.AddAzureMonitorMetricExporter();
Non è possibile estendere la distribuzione Java con librerie di strumentazione della community. Per richiedere di includere un'altra libreria di strumentazione, aprire un ticket nella pagina GitHub. È possibile trovare un collegamento alla pagina GitHub in Passaggi successivi.
Non è possibile usare librerie di strumentazione della community con applicazioni native Java GraalVM.
Altre strumentazioni OpenTelemetry sono disponibili qui e possono essere aggiunte tramite TraceHandler in ApplicationInsightsClient:
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics, trace, ProxyTracerProvider } = require("@opentelemetry/api");
// Import the OpenTelemetry instrumentation registration function and Express instrumentation
const { registerInstrumentations } = require( "@opentelemetry/instrumentation");
const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
// Get the OpenTelemetry tracer provider and meter provider
const tracerProvider = (trace.getTracerProvider() as ProxyTracerProvider).getDelegate();
const meterProvider = metrics.getMeterProvider();
// Enable Azure Monitor integration
useAzureMonitor();
// Register the Express instrumentation
registerInstrumentations({
// List of instrumentations to register
instrumentations: [
new ExpressInstrumentation(), // Express instrumentation
],
// OpenTelemetry tracer provider
tracerProvider: tracerProvider,
// OpenTelemetry meter provider
meterProvider: meterProvider
});
Per aggiungere una libreria di strumentazione della community (non ufficialmente supportata/inclusa nella distribuzione di Monitoraggio di Azure), è possibile instrumentare direttamente con le strumentazioni. L'elenco delle librerie di strumentazione della community è disponibile qui.
Nota
Non è consigliabile instrumentare manualmente una libreria di strumentazione supportata con instrument() insieme alla distribuzione configure_azure_monitor(). Questo non è uno scenario supportato e potrebbe verificarsi un comportamento indesiderato per i dati di telemetria.
# Import the `configure_azure_monitor()`, `SQLAlchemyInstrumentor`, `create_engine`, and `text` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
from sqlalchemy import create_engine, text
# Configure OpenTelemetry to use Azure Monitor.
configure_azure_monitor()
# Create a SQLAlchemy engine.
engine = create_engine("sqlite:///:memory:")
# SQLAlchemy instrumentation is not officially supported by this package, however, you can use the OpenTelemetry `instrument()` method manually in conjunction with `configure_azure_monitor()`.
SQLAlchemyInstrumentor().instrument(
engine=engine,
)
# Database calls using the SQLAlchemy library will be automatically captured.
with engine.connect() as conn:
result = conn.execute(text("select 'hello world'"))
print(result.all())
Raccogliere dati di telemetria personalizzati
Questa sezione illustra come raccogliere dati di telemetria personalizzati dall'applicazione.
A seconda della lingua e del tipo di segnale, esistono diversi modi per raccogliere dati di telemetria personalizzati, tra cui:
API OpenTelemetry
Librerie di registrazione/metriche specifiche del linguaggio
La tabella seguente rappresenta i tipi di telemetria personalizzati attualmente supportati:
Lingua
Eventi personalizzati
Metriche personalizzate
Dipendenze
Eccezioni
Visualizzazioni pagina
Richieste
Tracce
ASP.NET Core
API OpenTelemetry
Sì
Sì
Sì
Sì
ILoggerAPI
Sì
API IA classica
Java
API OpenTelemetry
Sì
Sì
Sì
Sì
Logback, Log4j, JUL
Sì
Sì
Metriche di Micrometer
Sì
API IA classica
Sì
Sì
Sì
Sì
Sì
Sì
Sì
Node.JS
API OpenTelemetry
Sì
Sì
Sì
Sì
Python
API OpenTelemetry
Sì
Sì
Sì
Sì
Modulo di registrazione Python
Sì
Estensione eventi
Sì
Sì
Nota
Application Insights Java 3.x è in ascolto dei dati di telemetria inviati all'API classica di Application Insights. Analogamente, Application Insights Node.js 3.x raccoglie gli eventi creati con l'API classica di Application Insights. In questo modo, l'aggiornamento risulta più semplice e colma il divario nel supporto dei dati di telemetria personalizzati, fino a quando tutti i tipi di telemetria personalizzati non saranno supportati tramite l'API OpenTelemetry.
Aggiungere le metriche personalizzate
In questo contesto, le metriche personalizzate si riferiscono alla strumentazione manuale del codice per raccogliere metriche aggiuntive oltre a quanto raccolto automaticamente dalle librerie di strumentazione OpenTelemetry.
L'API OpenTelemetry offre sei “strumenti” di metrica per coprire vari scenari di metrica ed è necessario scegliere il “tipo di aggregazione” corretto durante la visualizzazione delle metriche in Esplora metriche. Questo requisito è vero quando si usa l'API metrica OpenTelemetry per inviare metriche e quando si usa una libreria di strumentazione.
La tabella seguente illustra i tipi di aggregazione consigliati per ognuno degli strumenti di metrica di OpenTelemetry.
Strumento OpenTelemetry
Tipo di aggregazione di Monitoraggio di Azure
Contatore
Sum
Contatore asincrono
Sum
Istogramma
Min, Max, Media, Somma e Numero
Misuratore asincrono
Media
UpDownCounter
Sum
UpDownCounter asincrono
Sum
Attenzione
I tipi di aggregazione diversi da quelli mostrati nella tabella in genere non sono significativi.
La specifica OpenTelemetry descrive gli strumenti e fornisce esempi dei contesti in cui possono essere usati.
Suggerimento
L'istogramma è il più versatile e più strettamente equivalente all'API classica GetMetric di Application Insights. Monitoraggio di Azure attualmente semplifica lo strumento istogramma nei cinque tipi di aggregazione supportati e il supporto per i percentili è in corso. Anche se meno versatili, altri strumenti OpenTelemetry hanno un impatto minore sulle prestazioni dell'applicazione.
L'avvio dell'applicazione deve sottoscrivere un contatore in base al nome:
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Meter deve essere inizializzato utilizzando lo stesso nome:
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new histogram metric named "FruitSalePrice".
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");
// Create a new Random object.
var rand = new Random();
// Record a few random sale prices for apples and lemons, with different colors.
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "green"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Create a new Histogram metric named "FruitSalePrice".
// This metric will track the distribution of fruit sale prices.
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");
// Create a new Random object. This object will be used to generate random sale prices.
var rand = new Random();
// Record a few random sale prices for apples and lemons, with different colors.
// Each record includes a timestamp, a value, and a set of attributes.
// The attributes can be used to filter and analyze the metric data.
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "green"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
histogram.record(1.0);
histogram.record(100.0);
histogram.record(30.0);
}
}
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
histogram.record(1.0);
histogram.record(100.0);
histogram.record(30.0);
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the meter for the "testMeter" namespace
const meter = metrics.getMeter("testMeter");
// Create a histogram metric
let histogram = meter.createHistogram("histogram");
// Record values to the histogram metric with different tags
histogram.record(1, { "testKey": "testValue" });
histogram.record(30, { "testKey": "testValue2" });
histogram.record(100, { "testKey2": "testValue" });
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
# 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 a meter provider and a meter with the name "otel_azure_monitor_histogram_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_histogram_demo")
# Record three values to the histogram.
histogram = meter.create_histogram("histogram")
histogram.record(1.0, {"test_key": "test_value"})
histogram.record(100.0, {"test_key2": "test_value"})
histogram.record(30.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
L'avvio dell'applicazione deve sottoscrivere un contatore in base al nome:
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Meter deve essere inizializzato utilizzando lo stesso nome:
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new counter metric named "MyFruitCounter".
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
// Record the number of fruits sold, grouped by name and color.
myFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(1, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(2, new("name", "apple"), new("color", "green"));
myFruitCounter.Add(5, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(4, new("name", "lemon"), new("color", "yellow"));
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Create a new counter metric named "MyFruitCounter".
// This metric will track the number of fruits sold.
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
// Record the number of fruits sold, grouped by name and color.
myFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(1, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(2, new("name", "apple"), new("color", "green"));
myFruitCounter.Add(5, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(4, new("name", "lemon"), new("color", "yellow"));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
LongCounter myFruitCounter = meter
.counterBuilder("MyFruitCounter")
.build();
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "green"));
myFruitCounter.add(5, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(4, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
}
}
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the meter for the "testMeter" namespace
const meter = metrics.getMeter("testMeter");
// Create a counter metric
let counter = meter.createCounter("counter");
// Add values to the counter metric with different tags
counter.add(1, { "testKey": "testValue" });
counter.add(5, { "testKey2": "testValue" });
counter.add(3, { "testKey": "testValue2" });
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
# 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 a meter provider and a meter with the name "otel_azure_monitor_counter_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_counter_demo")
# Create a counter metric with the name "counter".
counter = meter.create_counter("counter")
# Add three values to the counter.
# The first argument to the `add()` method is the value to add.
# The second argument is a dictionary of dimensions.
# Dimensions are used to group related metrics together.
counter.add(1.0, {"test_key": "test_value"})
counter.add(5.0, {"test_key2": "test_value"})
counter.add(3.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
L'avvio dell'applicazione deve sottoscrivere un contatore in base al nome:
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Meter deve essere inizializzato utilizzando lo stesso nome:
// Get the current process.
var process = Process.GetCurrentProcess();
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new observable gauge metric named "Thread.State".
// This metric will track the state of each thread in the current process.
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));
private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
// Iterate over all threads in the current process.
foreach (ProcessThread thread in process.Threads)
{
// Create a measurement for each thread, including the thread state, process ID, and thread ID.
yield return new((int)thread.ThreadState, new("ProcessId", process.Id), new("ThreadId", thread.Id));
}
}
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Get the current process.
var process = Process.GetCurrentProcess();
// Create a new observable gauge metric named "Thread.State".
// This metric will track the state of each thread in the current process.
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
// Iterate over all threads in the current process.
foreach (ProcessThread thread in process.Threads)
{
// Create a measurement for each thread, including the thread state, process ID, and thread ID.
yield return new((int)thread.ThreadState, new("ProcessId", process.Id), new("ThreadId", thread.Id));
}
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
meter.gaugeBuilder("gauge")
.buildWithCallback(
observableMeasurement -> {
double randomNumber = Math.floor(Math.random() * 100);
observableMeasurement.record(randomNumber, Attributes.of(AttributeKey.stringKey("testKey"), "testValue"));
});
}
}
// Import the useAzureMonitor function and the metrics module from the @azure/monitor-opentelemetry and @opentelemetry/api packages, respectively.
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration.
useAzureMonitor();
// Get the meter for the "testMeter" meter name.
const meter = metrics.getMeter("testMeter");
// Create an observable gauge metric with the name "gauge".
let gauge = meter.createObservableGauge("gauge");
// Add a callback to the gauge metric. The callback will be invoked periodically to generate a new value for the gauge metric.
gauge.addCallback((observableResult: ObservableResult) => {
// Generate a random number between 0 and 99.
let randomNumber = Math.floor(Math.random() * 100);
// Set the value of the gauge metric to the random number.
observableResult.observe(randomNumber, {"testKey": "testValue"});
});
# Import the necessary packages.
from typing import Iterable
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
from opentelemetry.metrics import CallbackOptions, Observation
# 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 a meter provider and a meter with the name "otel_azure_monitor_gauge_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_gauge_demo")
# Define two observable gauge generators.
# The first generator yields a single observation with the value 9.
# The second generator yields a sequence of 10 observations with the value 9 and a different dimension value for each observation.
def observable_gauge_generator(options: CallbackOptions) -> Iterable[Observation]:
yield Observation(9, {"test_key": "test_value"})
def observable_gauge_sequence(options: CallbackOptions) -> Iterable[Observation]:
observations = []
for i in range(10):
observations.append(
Observation(9, {"test_key": i})
)
return observations
# Create two observable gauges using the defined generators.
gauge = meter.create_observable_gauge("gauge", [observable_gauge_generator])
gauge2 = meter.create_observable_gauge("gauge2", [observable_gauge_sequence])
# Wait for background execution.
input()
Aggiungere eccezioni personalizzate
Selezionare le librerie di strumentazione che segnalano automaticamente le eccezioni ad Application Insights.
Tuttavia, potrebbe essere necessario segnalare manualmente le eccezioni oltre al report delle librerie di strumentazione.
Ad esempio, le eccezioni rilevate dal codice non vengono in genere segnalate. È possibile segnalarle per attirare l'attenzione sulle esperienze pertinenti, tra cui la sezione errori e le viste delle transazioni end-to-end.
// Start a new activity named "ExceptionExample".
using (var activity = activitySource.StartActivity("ExceptionExample"))
{
// Try to execute some code.
try
{
throw new Exception("Test exception");
}
// If an exception is thrown, catch it and set the activity status to "Error".
catch (Exception ex)
{
activity?.SetStatus(ActivityStatusCode.Error);
activity?.RecordException(ex);
}
}
Per registrare un'eccezione usando ILogger:
// Create a logger using the logger factory. The logger category name is used to filter and route log messages.
var logger = loggerFactory.CreateLogger(logCategoryName);
// Try to execute some code.
try
{
throw new Exception("Test Exception");
}
catch (Exception ex)
{
// Log an error message with the exception. The log level is set to "Error" and the event ID is set to 0.
// The log message includes a template and a parameter. The template will be replaced with the value of the parameter when the log message is written.
logger.Log(
logLevel: LogLevel.Error,
eventId: 0,
exception: ex,
message: "Hello {name}.",
args: new object[] { "World" });
}
Per registrare un'eccezione usando un'attività:
// Start a new activity named "ExceptionExample".
using (var activity = activitySource.StartActivity("ExceptionExample"))
{
// Try to execute some code.
try
{
throw new Exception("Test exception");
}
// If an exception is thrown, catch it and set the activity status to "Error".
catch (Exception ex)
{
activity?.SetStatus(ActivityStatusCode.Error);
activity?.RecordException(ex);
}
}
Per registrare un'eccezione usando ILogger:
// Create a logger using the logger factory. The logger category name is used to filter and route log messages.
var logger = loggerFactory.CreateLogger("ExceptionExample");
try
{
// Try to execute some code.
throw new Exception("Test Exception");
}
catch (Exception ex)
{
// Log an error message with the exception. The log level is set to "Error" and the event ID is set to 0.
// The log message includes a template and a parameter. The template will be replaced with the value of the parameter when the log message is written.
logger.Log(
logLevel: LogLevel.Error,
eventId: 0,
exception: ex,
message: "Hello {name}.",
args: new object[] { "World" });
}
È possibile usare opentelemetry-api per aggiornare lo stato di un intervallo e registrare le eccezioni.
Aggiungere opentelemetry-api-1.0.0.jar (o versione successiva) all'applicazione:
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { trace } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the tracer for the "testTracer" namespace
const tracer = trace.getTracer("testTracer");
// Start a span with the name "hello"
let span = tracer.startSpan("hello");
// Try to throw an error
try{
throw new Error("Test Error");
}
// Catch the error and record it to the span
catch(error){
span.recordException(error);
}
L’SDK Python OpenTelemetry viene implementato in modo che le eccezioni generate vengano acquisite e registrate automaticamente. Vedere il codice di esempio seguente per un esempio di questo comportamento:
# Import the necessary packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# 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 a tracer for the current module.
tracer = trace.get_tracer("otel_azure_monitor_exception_demo")
# Exception events
try:
# Start a new span with the name "hello".
with tracer.start_as_current_span("hello") as span:
# This exception will be automatically recorded
raise Exception("Custom exception message.")
except Exception:
print("Exception raised")
Se si desidera registrare manualmente le eccezioni, è possibile disabilitare tale opzione all'interno del gestore del contesto e usare record_exception() direttamente, come illustrato nell'esempio seguente:
...
# Start a new span with the name "hello" and disable exception recording.
with tracer.start_as_current_span("hello", record_exception=False) as span:
try:
# Raise an exception.
raise Exception("Custom exception message.")
except Exception as ex:
# Manually record exception
span.record_exception(ex)
...
Aggiungere intervalli personalizzati
È possibile aggiungere un intervallo personalizzato in due scenari. In primo luogo, quando è presente una richiesta di dipendenza non già raccolta da una libreria di strumentazione. In secondo luogo, quando si vuole modellare un processo dell'applicazione come intervallo nella visualizzazione delle transazioni end-to-end.
Le classi Activity e ActivitySource dello spazio dei nomi System.Diagnostics rappresentano rispettivamente i concetti OpenTelemetry di Span e Tracer. È possibile creare ActivitySource direttamente usando il relativo costruttore anziché TracerProvider. Ogni classe ActivitySource deve essere connessa in modo esplicito a TracerProvider tramite AddSource(). Ciò è dovuto al fatto che parti dell'API di traccia OpenTelemetry vengono incorporate direttamente nel runtime .NET. Per altre informazioni, vedere Introduzione all'API di traccia .NET OpenTelemetry.
// Define an activity source named "ActivitySourceName". This activity source will be used to create activities for all requests to the application.
internal static readonly ActivitySource activitySource = new("ActivitySourceName");
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry tracer provider to add a source named "ActivitySourceName". This will ensure that all activities created by the activity source are traced.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddSource("ActivitySourceName"));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core application.
var app = builder.Build();
// Map a GET request to the root path ("/") to the specified action.
app.MapGet("/", () =>
{
// Start a new activity named "CustomActivity". This activity will be traced and the trace data will be sent to Azure Monitor.
using (var activity = activitySource.StartActivity("CustomActivity"))
{
// your code here
}
// Return a response message.
return $"Hello World!";
});
// Start the ASP.NET Core application.
app.Run();
StartActivity per impostazione predefinita è ActivityKind.Internal, ma è possibile specificare qualsiasi altro ActivityKind.
ActivityKind.Client, ActivityKind.Producer e ActivityKind.Internal vengono mappati a dependencies Application Insights.
ActivityKind.Server e ActivityKind.Consumer vengono mappati a requests Application Insights.
Nota
Le classi Activity e ActivitySource dello spazio dei nomi System.Diagnostics rappresentano rispettivamente i concetti OpenTelemetry di Span e Tracer. È possibile creare ActivitySource direttamente usando il relativo costruttore anziché TracerProvider. Ogni classe ActivitySource deve essere connessa in modo esplicito a TracerProvider tramite AddSource(). Ciò è dovuto al fatto che parti dell'API di traccia OpenTelemetry vengono incorporate direttamente nel runtime .NET. Per altre informazioni, vedere Introduzione all'API di traccia .NET OpenTelemetry.
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("ActivitySourceName")
.AddAzureMonitorTraceExporter()
.Build();
// Create an activity source named "ActivitySourceName".
var activitySource = new ActivitySource("ActivitySourceName");
// Start a new activity named "CustomActivity". This activity will be traced and the trace data will be sent to Azure Monitor.
using (var activity = activitySource.StartActivity("CustomActivity"))
{
// your code here
}
StartActivity per impostazione predefinita è ActivityKind.Internal, ma è possibile specificare qualsiasi altro ActivityKind.
ActivityKind.Client, ActivityKind.Producer e ActivityKind.Internal vengono mappati a dependencies Application Insights.
ActivityKind.Server e ActivityKind.Consumer vengono mappati a requests Application Insights.
Usare l'annotazione OpenTelemetry
Il modo più semplice per aggiungere intervalli personalizzati consiste nell'usare l'annotazione @WithSpan OpenTelemetry.
Gli intervalli popolano le tabelle requests e dependencies in Application Insights.
Aggiungere opentelemetry-instrumentation-annotations-1.32.0.jar (o versione successiva) all'applicazione:
Per impostazione predefinita, l'intervallo finisce nella tabella dependencies con il tipo di dipendenza InProc.
Per i metodi che rappresentano un processo in background non acquisito dalla strumentazione automatica, è consigliabile applicare l'attributo kind = SpanKind.SERVER all'annotazione @WithSpan per assicurarsi che vengano visualizzati nella tabella requests di Application Insights.
Usare l'API OpenTelemetry
Se l'annotazione OpenTelemetry @WithSpan precedente non soddisfa le proprie esigenze, è possibile aggiungere gli intervalli usando l'API OpenTelemetry.
Aggiungere opentelemetry-api-1.0.0.jar (o versione successiva) all'applicazione:
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = openTelemetry.getTracer("com.example");
Creare un intervallo, impostarlo come corrente e quindi terminarlo:
Span span = tracer.spanBuilder("my first span").startSpan();
try (Scope ignored = span.makeCurrent()) {
// do stuff within the context of this
} catch (Throwable t) {
span.recordException(t);
} finally {
span.end();
}
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { trace } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the tracer for the "testTracer" namespace
const tracer = trace.getTracer("testTracer");
// Start a span with the name "hello"
let span = tracer.startSpan("hello");
// End the span
span.end();
L'API OpenTelemetry può essere usata per aggiungere intervalli personalizzati, visualizzati nelle tabelle requests e dependencies in Application Insights.
Nell'esempio di codice viene illustrato come usare il metodo tracer.start_as_current_span() per iniziare, impostare l'intervallo corrente e terminare l'intervallo all'interno del relativo contesto.
...
# Import the necessary packages.
from opentelemetry import trace
# Get a tracer for the current module.
tracer = trace.get_tracer(__name__)
# Start a new span with the name "my first span" and make it the current span.
# The "with" context manager starts, makes the span current, and ends the span within it's context
with tracer.start_as_current_span("my first span") as span:
try:
# Do stuff within the context of this span.
# All telemetry generated within this scope will be attributed to this span.
except Exception as ex:
# Record the exception on the span.
span.record_exception(ex)
...
Per impostazione predefinita, l'intervallo si trova nella tabella dependencies con un tipo di dipendenza InProc.
Se il metodo rappresenta un processo in background non ancora acquisito dalla strumentazione automatica, è consigliabile impostare l'attributo kind = SpanKind.SERVER per assicurarsi che venga visualizzato nella tabella requests di Application Insights.
...
# Import the necessary packages.
from opentelemetry import trace
from opentelemetry.trace import SpanKind
# Get a tracer for the current module.
tracer = trace.get_tracer(__name__)
# Start a new span with the name "my request span" and the kind set to SpanKind.SERVER.
with tracer.start_as_current_span("my request span", kind=SpanKind.SERVER) as span:
# Do stuff within the context of this span.
...
Inviare dati di telemetria personalizzati usando l'API classica di Application Insights
È consigliabile usare le API OpenTelemetry quando possibile, ma potrebbero esserci alcuni scenari in cui è necessario usare l'API classica di Application Insights.
Non è possibile inviare dati di telemetria personalizzati usando l'API classica di Application Insights in Java nativo.
Per aggiungere eventi personalizzati o accedere all'API di Application Insights, sostituire il pacchetto @azure/monitor-opentelemetry con il pacchetto applicationinsightsBeta v3. Esso offre gli stessi metodi e interfacce e tutto il codice di esempio per @azure/monitor-opentelemetry si applica al pacchetto beta v3.
// Import the TelemetryClient class from the Application Insights SDK for JavaScript.
const { TelemetryClient } = require("applicationinsights");
// Create a new TelemetryClient instance.
const telemetryClient = new TelemetryClient();
Usare quindi il TelemetryClient per inviare dati di telemetria personalizzati:
Eventi
// Create an event telemetry object.
let eventTelemetry = {
name: "testEvent"
};
// Send the event telemetry object to Azure Monitor Application Insights.
telemetryClient.trackEvent(eventTelemetry);
Registri
// Create a trace telemetry object.
let traceTelemetry = {
message: "testMessage",
severity: "Information"
};
// Send the trace telemetry object to Azure Monitor Application Insights.
telemetryClient.trackTrace(traceTelemetry);
Eccezioni
// Try to execute a block of code.
try {
...
}
// If an error occurs, catch it and send it to Azure Monitor Application Insights as an exception telemetry item.
catch (error) {
let exceptionTelemetry = {
exception: error,
severity: "Critical"
};
telemetryClient.trackException(exceptionTelemetry);
}
A differenza di altri linguaggi, Python non ha un SDK Application Insights. È possibile soddisfare tutte le esigenze di monitoraggio con la distribuzione OpenTelemetry di Monitoraggio di Azure, ad eccezione dell'invio di customEvents. Fino a quando l'API Eventi OpenTelemetry non si stabilizza, usare l'estensione eventi di Monitoraggio di Azure con la distribuzione OpenTelemetry di Monitoraggio di Azure per inviare customEvents ad Application Insights.
Usare l'API track_event offerta nell'estensione per l'invio di customEvents:
...
from azure.monitor.events.extension import track_event
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor()
# Use the track_event() api to send custom event telemetry
# Takes event name and custom dimensions
track_event("Test event", {"key1": "value1", "key2": "value2"})
input()
...
Modificare la telemetria
Questa sezione illustra come modificare i dati di telemetria.
Aggiungere attributi intervallo
Questi attributi possono includere l'aggiunta di una proprietà personalizzata ai dati di telemetria. È inoltre possibile usare gli attributi per impostare campi facoltativi nello schema di Application Insights, ad esempio IP client.
Aggiungere una proprietà personalizzata a un intervallo
Tutti gli attributi aggiunti agli intervalli vengono esportati come proprietà personalizzate. Popolano il campo customDimensions della tabella richieste, dipendenze, tracce o eccezioni.
Aggiungere un processore di estensione personalizzato.
Suggerimento
Il vantaggio di usare le opzioni fornite dalle librerie di strumentazione, quando sono disponibili, è il fatto che sia disponibile che l'intero contesto. Di conseguenza, gli utenti possono effettuare una selezione per aggiungere o filtrare altri attributi. Ad esempio, l'opzione arricchire nella libreria di strumentazione HttpClient consente agli utenti di accedere allo stesso HttpRequestMessage e HttpResponseMessage. Da lì, possono selezionare qualsiasi elemento e archiviarlo come attributo.
Molte librerie di strumentazione offrono un'opzione di arricchimento. Per indicazioni, vedere i file leggimi delle singole librerie di strumentazione:
Aggiungere il processore illustrato qui prima di aggiungere Monitoraggio di Azure.
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry tracer provider to add a new processor named ActivityEnrichingProcessor.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddProcessor(new ActivityEnrichingProcessor()));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core application.
var app = builder.Build();
// Start the ASP.NET Core application.
app.Run();
Aggiungere ActivityEnrichingProcessor.cs al progetto con il codice seguente:
public class ActivityEnrichingProcessor : BaseProcessor<Activity>
{
public override void OnEnd(Activity activity)
{
// The updated activity will be available to all processors which are called after this processor.
activity.DisplayName = "Updated-" + activity.DisplayName;
activity.SetTag("CustomDimension1", "Value1");
activity.SetTag("CustomDimension2", "Value2");
}
}
Per aggiungere attributi intervallo, usare uno dei due modi seguenti:
Usare le opzioni fornite dalle librerie di strumentazione.
Aggiungere un processore di estensione personalizzato.
Suggerimento
Il vantaggio di usare le opzioni fornite dalle librerie di strumentazione, quando sono disponibili, è il fatto che sia disponibile che l'intero contesto. Di conseguenza, gli utenti possono effettuare una selezione per aggiungere o filtrare altri attributi. Ad esempio, l'opzione arricchire nella libreria di strumentazione HttpClient consente agli utenti di accedere allo stesso httpRequestMessage. Da lì, possono selezionare qualsiasi elemento e archiviarlo come attributo.
Molte librerie di strumentazione offrono un'opzione di arricchimento. Per indicazioni, vedere i file leggimi delle singole librerie di strumentazione:
Aggiungere il processore illustrato prima dell'utilità di esportazione di Monitoraggio di Azure.
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
// Add a source named "OTel.AzureMonitor.Demo".
.AddSource("OTel.AzureMonitor.Demo") // Add a new processor named ActivityEnrichingProcessor.
.AddProcessor(new ActivityEnrichingProcessor()) // Add the Azure Monitor trace exporter.
.AddAzureMonitorTraceExporter() // Add the Azure Monitor trace exporter.
.Build();
Aggiungere ActivityEnrichingProcessor.cs al progetto con il codice seguente:
public class ActivityEnrichingProcessor : BaseProcessor<Activity>
{
// The OnEnd method is called when an activity is finished. This is the ideal place to enrich the activity with additional data.
public override void OnEnd(Activity activity)
{
// Update the activity's display name.
// The updated activity will be available to all processors which are called after this processor.
activity.DisplayName = "Updated-" + activity.DisplayName;
// Set custom tags on the activity.
activity.SetTag("CustomDimension1", "Value1");
activity.SetTag("CustomDimension2", "Value2");
}
}
È possibile usare opentelemetry-api per aggiungere attributi agli intervalli.
L'aggiunta di uno o più attributi intervallo popola il campo customDimensions della tabella requests, dependencies, traces o exceptions.
Aggiungere opentelemetry-api-1.0.0.jar (o versione successiva) all'applicazione:
...
# Import the necessary packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Create a SpanEnrichingProcessor instance.
span_enrich_processor = SpanEnrichingProcessor()
# 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>",
# Configure the custom span processors to include span enrich processor.
span_processors=[span_enrich_processor],
)
...
Aggiungere SpanEnrichingProcessor al progetto con il codice seguente:
# Import the SpanProcessor class from the opentelemetry.sdk.trace module.
from opentelemetry.sdk.trace import SpanProcessor
class SpanEnrichingProcessor(SpanProcessor):
def on_end(self, span):
# Prefix the span name with the string "Updated-".
span._name = "Updated-" + span.name
# Add the custom dimension "CustomDimension1" with the value "Value1".
span._attributes["CustomDimension1"] = "Value1"
# Add the custom dimension "CustomDimension2" with the value "Value2".
span._attributes["CustomDimension2"] = "Value2"
Impostare l'IP utente
È possibile popolare il campo client_IP delle richieste impostando un attributo sull'intervallo. Application Insights usa l'indirizzo IP per generare gli attributi di posizione utente e poi lo rimuove per impostazione predefinita.
// Add the client IP address to the activity as a tag.
// only applicable in case of activity.Kind == Server
activity.SetTag("client.address", "<IP Address>");
// Add the client IP address to the activity as a tag.
// only applicable in case of activity.Kind == Server
activity.SetTag("client.address", "<IP Address>");
...
// Import the SemanticAttributes class from the @opentelemetry/semantic-conventions package.
const { SemanticAttributes } = require("@opentelemetry/semantic-conventions");
// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {
onEnd(span) {
// Set the HTTP_CLIENT_IP attribute on the span to the IP address of the client.
span.attributes[SemanticAttributes.HTTP_CLIENT_IP] = "<IP Address>";
}
}
# Set the `http.client_ip` attribute of the span to the specified IP address.
span._attributes["http.client_ip"] = "<IP Address>"
Impostare l'ID utente o l'ID utente autenticato
È possibile popolare il campo user_Id o user_AuthenticatedId per le richieste usando le indicazioni seguenti. L'ID utente è un ID utente anonimo. L'ID utente autenticato è un ID utente noto.
Importante
Prima di impostare l'ID utente autenticato, consultare le leggi sulla privacy applicabili.
...
// Import the SemanticAttributes class from the @opentelemetry/semantic-conventions package.
import { SemanticAttributes } from "@opentelemetry/semantic-conventions";
// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {
onEnd(span: ReadableSpan) {
// Set the ENDUSER_ID attribute on the span to the ID of the user.
span.attributes[SemanticAttributes.ENDUSER_ID] = "<User ID>";
}
}
OpenTelemetry usa ILogger di .NET.
È possibile allegare dimensioni personalizzate ai log usando un modello di messaggio.
OpenTelemetry usa ILogger di .NET.
È possibile allegare dimensioni personalizzate ai log usando un modello di messaggio.
Logback, Log4j e java.util.logging vengono strumentati automaticamente. Il collegamento di dimensioni personalizzate ai log può essere eseguito in questi modi:
Log4j 2.0 MapMessage (una chiave MapMessage di "message" viene acquisita come messaggio di log)
La libreria di registrazione Python viene strumentata automaticamente. È possibile allegare dimensioni personalizzate ai log trasmettendo un dizionario nell'argomento extra dei log:
...
# Create a warning log message with the properties "key1" and "value1".
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
Filtrare i dati di telemetria
È possibile usare i modi seguenti per filtrare i dati di telemetria prima di uscire dall'applicazione.
Aggiungere il processore illustrato qui prima di aggiungere Monitoraggio di Azure.
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry tracer provider to add a new processor named ActivityFilteringProcessor.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddProcessor(new ActivityFilteringProcessor()));
// Configure the OpenTelemetry tracer provider to add a new source named "ActivitySourceName".
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddSource("ActivitySourceName"));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core application.
var app = builder.Build();
// Start the ASP.NET Core application.
app.Run();
Aggiungere ActivityFilteringProcessor.cs al progetto con il codice seguente:
public class ActivityFilteringProcessor : BaseProcessor<Activity>
{
// The OnStart method is called when an activity is started. This is the ideal place to filter activities.
public override void OnStart(Activity activity)
{
// prevents all exporters from exporting internal activities
if (activity.Kind == ActivityKind.Internal)
{
activity.IsAllDataRequested = false;
}
}
}
Se un'origine specifica non viene aggiunta in modo esplicito tramite AddSource("ActivitySourceName"), nessuna delle attività create tramite tale origine viene esportata.
Molte librerie di strumentazione offrono un'opzione di filtro. Per indicazioni, vedere i file leggimi delle singole librerie di strumentazione:
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("OTel.AzureMonitor.Demo") // Add a source named "OTel.AzureMonitor.Demo".
.AddProcessor(new ActivityFilteringProcessor()) // Add a new processor named ActivityFilteringProcessor.
.AddAzureMonitorTraceExporter() // Add the Azure Monitor trace exporter.
.Build();
Aggiungere ActivityFilteringProcessor.cs al progetto con il codice seguente:
public class ActivityFilteringProcessor : BaseProcessor<Activity>
{
// The OnStart method is called when an activity is started. This is the ideal place to filter activities.
public override void OnStart(Activity activity)
{
// prevents all exporters from exporting internal activities
if (activity.Kind == ActivityKind.Internal)
{
activity.IsAllDataRequested = false;
}
}
}
Se un'origine specifica non viene aggiunta in modo esplicito tramite AddSource("ActivitySourceName"), nessuna delle attività create tramite tale origine viene esportata.
// Import the useAzureMonitor function and the ApplicationInsightsOptions class from the @azure/monitor-opentelemetry package.
const { useAzureMonitor, ApplicationInsightsOptions } = require("@azure/monitor-opentelemetry");
// Import the HttpInstrumentationConfig class from the @opentelemetry/instrumentation-http package.
const { HttpInstrumentationConfig }= require("@opentelemetry/instrumentation-http");
// Import the IncomingMessage and RequestOptions classes from the http and https packages, respectively.
const { IncomingMessage } = require("http");
const { RequestOptions } = require("https");
// Create a new HttpInstrumentationConfig object.
const httpInstrumentationConfig: HttpInstrumentationConfig = {
enabled: true,
ignoreIncomingRequestHook: (request: IncomingMessage) => {
// Ignore OPTIONS incoming requests.
if (request.method === 'OPTIONS') {
return true;
}
return false;
},
ignoreOutgoingRequestHook: (options: RequestOptions) => {
// Ignore outgoing requests with the /test path.
if (options.path === '/test') {
return true;
}
return false;
}
};
// Create a new ApplicationInsightsOptions object.
const config: ApplicationInsightsOptions = {
instrumentationOptions: {
http: {
httpInstrumentationConfig
}
}
};
// Enable Azure Monitor integration using the useAzureMonitor function and the ApplicationInsightsOptions object.
useAzureMonitor(config);
Usare un processore personalizzato. È possibile usare un processore di intervallo personalizzato per escludere determinati intervalli dall'esportazione. Per contrassegnare gli intervalli da non esportare, impostare TraceFlag su DEFAULT.
In questo modo viene escluso l'endpoint illustrato nell'esempio Flask seguente:
...
# Import the Flask and Azure Monitor OpenTelemetry SDK libraries.
import flask
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 to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Create a Flask application.
app = flask.Flask(__name__)
# Define a route. Requests sent to this endpoint will not be tracked due to
# flask_config configuration.
@app.route("/ignore")
def ignore():
return "Request received but not tracked."
...
Usare un processore personalizzato. È possibile usare un processore di intervallo personalizzato per escludere determinati intervalli dall'esportazione. Per contrassegnare gli intervalli che non devono essere esportati, impostare TraceFlag su DEFAULT:
...
# Import the necessary libraries.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# 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>",
# Configure the custom span processors to include span filter processor.
span_processors=[span_filter_processor],
)
...
Aggiungere SpanFilteringProcessor al progetto con il codice seguente:
# Import the necessary libraries.
from opentelemetry.trace import SpanContext, SpanKind, TraceFlags
from opentelemetry.sdk.trace import SpanProcessor
# Define a custom span processor called `SpanFilteringProcessor`.
class SpanFilteringProcessor(SpanProcessor):
# Prevents exporting spans from internal activities.
def on_start(self, span, parent_context):
# Check if the span is an internal activity.
if span._kind is SpanKind.INTERNAL:
# Create a new span context with the following properties:
# * The trace ID is the same as the trace ID of the original span.
# * The span ID is the same as the span ID of the original span.
# * The is_remote property is set to `False`.
# * The trace flags are set to `DEFAULT`.
# * The trace state is the same as the trace state of the original span.
span._context = SpanContext(
span.context.trace_id,
span.context.span_id,
span.context.is_remote,
TraceFlags(TraceFlags.DEFAULT),
span.context.trace_state,
)
Ottenere l'ID di traccia o l'ID intervallo
È possibile ottenere Trace ID e Span ID dell'oggetto Span attualmente attivo attenendosi alla procedura seguente.
Le classi Activity e ActivitySource dello spazio dei nomi System.Diagnostics rappresentano rispettivamente i concetti OpenTelemetry di Span e Tracer. Ciò è dovuto al fatto che parti dell'API di traccia OpenTelemetry vengono incorporate direttamente nel runtime .NET. Per altre informazioni, vedere Introduzione all'API di traccia .NET OpenTelemetry.
// Get the current activity.
Activity activity = Activity.Current;
// Get the trace ID of the activity.
string traceId = activity?.TraceId.ToHexString();
// Get the span ID of the activity.
string spanId = activity?.SpanId.ToHexString();
Nota
Le classi Activity e ActivitySource dello spazio dei nomi System.Diagnostics rappresentano rispettivamente i concetti OpenTelemetry di Span e Tracer. Ciò è dovuto al fatto che parti dell'API di traccia OpenTelemetry vengono incorporate direttamente nel runtime .NET. Per altre informazioni, vedere Introduzione all'API di traccia .NET OpenTelemetry.
// Get the current activity.
Activity activity = Activity.Current;
// Get the trace ID of the activity.
string traceId = activity?.TraceId.ToHexString();
// Get the span ID of the activity.
string spanId = activity?.SpanId.ToHexString();
È possibile usare opentelemetry-api per ottenere l'ID di traccia o l'ID intervallo.
Aggiungere opentelemetry-api-1.0.0.jar (o versione successiva) all'applicazione:
Ottenere l'ID di traccia della richiesta e l'ID intervallo nel codice:
// Import the trace module from the OpenTelemetry API.
const { trace } = require("@opentelemetry/api");
// Get the span ID and trace ID of the active span.
let spanId = trace.getActiveSpan().spanContext().spanId;
let traceId = trace.getActiveSpan().spanContext().traceId;
Ottenere l'ID di traccia della richiesta e l'ID intervallo nel codice:
# Import the necessary libraries.
from opentelemetry import trace
# Get the trace ID and span ID of the current span.
trace_id = trace.get_current_span().get_span_context().trace_id
span_id = trace.get_current_span().get_span_context().span_id
Questa sezione fornisce le risposte alle domande comuni.
Che cos'è OpenTelemetry?
Si tratta di un nuovo standard open source per l'osservabilità. Per altre informazioni, vedere OpenTelemetry.
Perché Monitoraggio di Azure Microsoft investe in OpenTelemetry?
Microsoft è tra i maggiori collaboratori di OpenTelemetry.
Le principali proposte di valore di OpenTelemetry sono il fatto che sia indipendente dal fornitore e che offra API/SDK coerenti in tutti i linguaggi.
Riteniamo che nel tempo OpenTelemetry consentirà ai clienti di Monitoraggio di Azure di osservare le applicazioni scritte in altri linguaggi oltre ai linguaggi supportati. Espande anche i tipi di dati che è possibile raccogliere tramite un set completo di librerie di strumentazione. Inoltre, OpenTelemetry Software Development Kit (SDK) tende a essere più efficiente su larga scala rispetto ai predecessori, gli SDK di Application Insights.
Infine, OpenTelemetry si allinea alla strategia di Microsoft che si prefigge di adottare l'open source.
Che cos'è la distribuzione OpenTelemetry di Monitoraggio di Azure?
Può essere considerata un wrapper sottile che aggrega tutti i componenti OpenTelemetry per un'esperienza di prima classe in Azure. In OpenTelemetry questo wrapper è detto anche distribuzione.
Perché è consigliabile usare la distribuzione OpenTelemetry di Monitoraggio di Azure?
L'uso della distribuzione OpenTelemetry di Azure Monitor presenta diversi vantaggi rispetto a OpenTelemetry nativo della community:
Riduce il lavoro di abilitazione
È supportato da Microsoft
Include funzionalità specifiche di Azure, ad esempio:
Campionamento compatibile con gli SDK classici di Application Insights
Nello spirito di OpenTelemetry, abbiamo progettato la distribuzione in modo che sia aperta ed estendibile. Ad esempio, è possibile aggiungere:
Esportazione del protocollo OTLP (OpenTelemetry Protocol) e invio simultaneo a una seconda destinazione
Altre librerie di strumentazione non incluse nella distribuzione
Poiché la distribuzione fornisce una distribuzione OpenTelemetry, la distribuzione supporta qualsiasi elemento supportato da OpenTelemetry. Ad esempio, è possibile aggiungere altri processori di telemetria, utilità di esportazione o librerie di strumentazione, se OpenTelemetry li supporta.
Nota
La distribuzione imposta il campionatore su un campionatore personalizzato a frequenza fissa per Application Insights. È possibile passare a un campionatore diverso, ma ciò potrebbe disabilitare alcune delle funzionalità incluse della distribuzione.
Per altre informazioni sul campionatore supportato, vedere la sezione Abilitare il campionamento di Configurare OpenTelemetry di Monitoraggio di Azure.
Per i linguaggi privi di un utilità di esportazione OpenTelemetry autonoma supportata, la distribuzione OpenTelemetry di Monitoraggio di Azure è l'unico modo attualmente supportato per usare OpenTelemetry con Monitoraggio di Azure. Per i linguaggi con un utilità di esportazione OpenTelemetry autonoma supportata, è possibile usare la distribuzione OpenTelemetry di Monitoraggio di Azure o l'utilità di esportazione OpenTelemetry autonoma appropriata a seconda dello scenario di telemetria. Per altre informazioni, vedere Quando usare l'utilità di esportazione OpenTelemetry di Monitoraggio di Azure?.
Come è possibile testare la distribuzione OpenTelemetry di Monitoraggio di Azure?
L'adozione di OpenTelemetry ora consente di non dover effettuare la migrazione in un secondo momento.
Quando è consigliabile usare l'utilità di esportazione OpenTelemetry di Monitoraggio di Azure?
Per ASP.NET Core, Java, Node.js e Python, è consigliabile usare la distribuzione OpenTelemetry di Monitoraggio di Azure. Si tratta di una riga di codice con cui iniziare.
Per tutti gli altri scenari .NET, inclusi ASP.NET classico, app console, Windows Forms (WinForms) e così via, è consigliabile usare l'utilità di esportazione OpenTelemetry di Monitoraggio di Azure .NET: Azure.Monitor.OpenTelemetry.Exporter.
❌ Questa funzionalità non è disponibile o non è applicabile.
È possibile usare OpenTelemetry per i Web browser?
Sì, ma non è consigliabile e Azure non lo supporta. OpenTelemetry JavaScript è fortemente ottimizzato per Node.js. È invece consigliabile usare l'SDK JavaScript Application Insights.
Per quando è prevista la disponibilità dell'SDK OpenTelemetry per l'uso nei Web browser?
L'SDK Web OpenTelemetry non ha una timeline di disponibilità determinata. Probabilmente serviranno diversi anni perché un SDK browser sia una valida alternativa all'SDK JavaScript di Application Insights.
Oggi è possibile testare OpenTelemetry in un Web browser?
La sandbox Web OpenTelemetry è un fork progettato per consentire il funzionamento di OpenTelemetry in un browser. Non è ancora possibile inviare dati di telemetria ad Application Insights. L'SDK non definisce eventi client generali.
L'esecuzione di Application Insights insieme a agenti concorrenti come AppDynamics, DataDog e NewRelic è supportata?
Alcuni clienti usano l'agente di raccolta OpenTelemetry come alternativa agente, anche se al momento Microsoft non supporta ufficialmente un approccio basato su agente per il monitoraggio delle applicazioni. Nel frattempo, la community open source ha contribuito a un'utilità di esportazione di Monitoraggio di Azure dell'agente di raccolta OpenTelemetry che alcuni clienti usano per inviare dati ad Application Insights di Monitoraggio di Azure. Questo non è supportato da Microsoft.
Qual è la differenza tra OpenCensus e OpenTelemetry?
OpenCensus è il precursore di OpenTelemetry. Microsoft ha contribuito a riunire OpenTracing e OpenCensus per creare OpenTelemetry, un unico standard di osservabilità a livello globale. L'SDK Python attualmente consigliato per la produzione per Monitoraggio di Azure si basa su OpenCensus. Microsoft si impegna a rendere Monitoraggio di Azure basato su OpenTelemetry.
In Grafana, perché vedo Status: 500. Can't visualize trace events using the trace visualizer?
È possibile provare a visualizzare i log di testo non elaborati anziché le tracce OpenTelemetry.
In Application Insights la tabella 'Traces' archivia i log di testo non elaborati a scopo diagnostico. Consentono di identificare e correlare le tracce associate alle richieste degli utenti, ad altri eventi e ai report delle eccezioni. Tuttavia, la tabella 'Traces' non contribuisce direttamente alla visualizzazione delle transazioni end-to-end (grafico a cascata) negli strumenti di visualizzazione come Grafana.
Con l'adozione crescente delle procedure native del cloud, esiste un'evoluzione nella raccolta e nella terminologia dei dati di telemetria. OpenTelemetry è diventato uno standard per la raccolta e la strumentazione dei dati di telemetria. In questo contesto, il termine 'Traces' ha assunto un nuovo significato. Anziché ai log non elaborati, 'Traces' in OpenTelemetry fa riferimento a una forma più completa e strutturata di dati di telemetria che include intervalli, che rappresentano singole unità di lavoro. Questi intervalli sono fondamentali per la creazione di viste di transazioni dettagliate, consentendo un monitoraggio e una diagnostica migliori delle applicazioni native del cloud.
Passaggio 1: abilitare la registrazione diagnostica
L'utilità di esportazione del Monitoraggio di Azure utilizza EventSource per la registrazione interna. I log dell'utilità di esportazione sono disponibili per qualsiasi EventListener mediante il consenso esplicito all'origine denominata OpenTelemetry-AzureMonitor-Exporter. Per conoscere i passaggi per la risoluzione dei problemi, vedere Risoluzione dei problemi OpenTelemetry su GitHub.
Passaggio 2: testare la connettività tra l'host dell'applicazione e il servizio di inserimento dati
Gli SDK e gli agenti di Application Insights inviano dati di telemetria per l'inserimento, ad esempio chiamate REST, agli endpoint di inserimento dati. Per testare la connettività dal server Web o dal computer host dell'applicazione con gli endpoint del servizio di inserimento dati, usare i comandi cURL o le richieste REST non elaborate da PowerShell. Per altre informazioni, vedere Risolvere i problemi di dati di telemetria mancanti delle applicazioni in Application Insights per Monitoraggio di Azure.
Problemi noti
Gli elementi seguenti sono problemi noti per le utilità di esportazione OpenTelemetry di Monitoraggio di Azure:
Nome dell'operazione mancante nei dati di telemetria delle dipendenze. La mancanza del nome dell'operazione causa errori e influisce negativamente sull'esperienza della scheda prestazioni.
Modello dispositivo mancante nei dati di telemetria delle richieste e delle dipendenze. La mancanza del modello dispositivo influisce negativamente sull'analisi della coorte del dispositivo.
Passaggio 1: abilitare la registrazione diagnostica
L'utilità di esportazione del Monitoraggio di Azure utilizza EventSource per la registrazione interna. I log dell'utilità di esportazione sono disponibili per qualsiasi EventListener mediante il consenso esplicito all'origine denominata OpenTelemetry-AzureMonitor-Exporter. Per conoscere i passaggi per la risoluzione dei problemi, vedere Risoluzione dei problemi OpenTelemetry su GitHub.
Passaggio 2: testare la connettività tra l'host dell'applicazione e il servizio di inserimento dati
Gli SDK e gli agenti di Application Insights inviano dati di telemetria per l'inserimento, ad esempio chiamate REST, agli endpoint di inserimento dati. Per testare la connettività dal server Web o dal computer host dell'applicazione con gli endpoint del servizio di inserimento dati, usare i comandi cURL o le richieste REST non elaborate da PowerShell. Per altre informazioni, vedere Risolvere i problemi di dati di telemetria mancanti delle applicazioni in Application Insights per Monitoraggio di Azure.
Problemi noti
Gli elementi seguenti sono problemi noti per le utilità di esportazione OpenTelemetry di Monitoraggio di Azure:
Nome dell'operazione mancante nei dati di telemetria delle dipendenze. La mancanza del nome dell'operazione causa errori e influisce negativamente sull'esperienza della scheda prestazioni.
Modello dispositivo mancante nei dati di telemetria delle richieste e delle dipendenze. La mancanza del modello dispositivo influisce negativamente sull'analisi della coorte del dispositivo.
Passaggio 1: abilitare la registrazione diagnostica
Passaggio 2: testare la connettività tra l'host dell'applicazione e il servizio di inserimento dati
Gli SDK e gli agenti di Application Insights inviano dati di telemetria per l'inserimento, ad esempio chiamate REST, agli endpoint di inserimento dati. Per testare la connettività dal server Web o dal computer host dell'applicazione con gli endpoint del servizio di inserimento dati, usare i comandi cURL o le richieste REST non elaborate da PowerShell. Per altre informazioni, vedere Risolvere i problemi di dati di telemetria mancanti delle applicazioni in Application Insights per Monitoraggio di Azure.
Problemi noti
Se si scarica la libreria client di Application Insights per l'installazione da un browser, talvolta il file JAR scaricato è danneggiato e ha dimensioni di circa la metà rispetto al file di origine. Se si verifica questo problema, scaricare il file JAR eseguendo il comando curl o wget, come illustrato nelle chiamate di comando dell'esempio seguente:
Le chiamate di comando dell'esempio si applicano ad Application Insights per Java versione 3.4.11. Per trovare il numero di versione e l'indirizzo URL della versione corrente di Application Insights per Java, vedere https://github.com/microsoft/ApplicationInsights-Java/releases.
I passaggi seguenti sono applicabili alle applicazioni native Spring Boot.
Passaggio 1: verificare la versione di OpenTelemetry
Durante l'avvio dell'applicazione potrebbe essere visualizzato il messaggio seguente:
WARN c.a.m.a.s.OpenTelemetryVersionCheckRunner - The OpenTelemetry version is not compatible with the spring-cloud-azure-starter-monitor dependency.
The OpenTelemetry version should be <version>
In questo caso, è necessario importare le distinte base di OpenTelemetry secondo le indicazioni della documentazione di OpenTelemetry nell'unità di avvio Spring Boot.
Passaggio 2: abilitare la diagnostica automatica
Se qualcosa non funziona come previsto, è possibile abilitare la diagnostica automatica a livello di DEBUG per ottenere informazioni dettagliate. A tale scopo, impostare il livello di diagnostica automatica su ERROR, WARN, INFO, DEBUG o TRACE usando la variabile di ambiente APPLICATIONINSIGHTS_SELF_DIAGNOSTICS_LEVEL.
Per abilitare la diagnostica automatica al livello DEBUG con un contenitore Docker in esecuzione, eseguire il comando seguente:
docker run -e APPLICATIONINSIGHTS_SELF_DIAGNOSTICS_LEVEL=DEBUG <image-name>
Nota
Sostituire <image-name> con il nome dell'immagine Docker di conseguenza.
Dichiarazione di non responsabilità sulle informazioni di terze parti
I prodotti di terzi citati in questo articolo sono prodotti da società indipendenti da Microsoft. Microsoft non rilascia alcuna garanzia implicita o esplicita relativa alle prestazioni o all'affidabilità di tali prodotti
Passaggio 1: abilitare la registrazione diagnostica
L'utilità di esportazione di Monitoraggio di Azure si avvale del logger dell'API OpenTelemetry per i log interni. Per abilitare il logger, eseguire il frammento di codice riportato di seguito:
Passaggio 2: testare la connettività tra l'host dell'applicazione e il servizio di inserimento dati
Gli SDK e gli agenti di Application Insights inviano dati di telemetria per l'inserimento, ad esempio chiamate REST, agli endpoint di inserimento dati. Per testare la connettività dal server Web o dal computer host dell'applicazione con gli endpoint del servizio di inserimento dati, usare i comandi cURL o le richieste REST non elaborate da PowerShell. Per altre informazioni, vedere Risolvere i problemi di dati di telemetria mancanti delle applicazioni in Application Insights per Monitoraggio di Azure.
Problemi noti
Gli elementi seguenti sono problemi noti per le utilità di esportazione OpenTelemetry di Monitoraggio di Azure:
Nome dell'operazione mancante nei dati di telemetria delle dipendenze. La mancanza del nome dell'operazione causa errori e influisce negativamente sull'esperienza della scheda prestazioni.
Modello dispositivo mancante nei dati di telemetria delle richieste e delle dipendenze. La mancanza del modello dispositivo influisce negativamente sull'analisi della coorte del dispositivo.
Nome del server di database mancante nel nome della dipendenza. Poiché il nome del server di database non è incluso, le utilità di esportazione OpenTelemetry aggregano erroneamente le tabelle con lo stesso nome in server diversi.
Passaggio 1: abilitare la registrazione diagnostica
L'utilità di esportazione di Monitoraggio di Microsoft Azure usa la libreria di registrazione standard Python per la registrazione interna. All'API OpenTelemetry e ai log dell'utilità di esportazione di Monitoraggio di Azure viene assegnato un livello di gravità di WARNING o ERROR per attività irregolare. Il livello di gravità INFO indica attività regolari o con esito positivo.
Per impostazione predefinita, la libreria di registrazione Python imposta il livello di gravità su WARNING. Pertanto, è necessario modificare il livello di gravità per visualizzare i log con tale impostazione della gravità. Il codice di esempio seguente illustra come generare i log di tutti i livelli di gravità nella console e in un file:
Passaggio 2: testare la connettività tra l'host dell'applicazione e il servizio di inserimento dati
Gli SDK e gli agenti di Application Insights inviano dati di telemetria per l'inserimento, ad esempio chiamate REST, agli endpoint di inserimento dati. Per testare la connettività dal server Web o dal computer host dell'applicazione con gli endpoint del servizio di inserimento dati, usare i comandi cURL o le richieste REST non elaborate da PowerShell. Per altre informazioni, vedere Risolvere i problemi di dati di telemetria mancanti delle applicazioni in Application Insights per Monitoraggio di Azure.
Passaggio 3: evitare dati di telemetria duplicati
Spesso i dati di telemetria duplicati sono causati dalla creazione di più istanze di processori o utilità di esportazione. Assicurarsi di eseguire una sola utilità di esportazione e un solo processore alla volta per ciascun pilastro dei dati di telemetria (log, metriche e traccia distribuita).
Nelle sezioni seguenti sono illustrati gli scenari nei quali si possono generare dati di telemetria duplicati.
Log di traccia duplicati in Funzioni di Azure
Se viene visualizzata una coppia di voci per ciascun log di traccia in Application Insights, probabilmente sono stati abilitati i seguenti tipi di strumentazione di registrazione:
Strumentazione di registrazione nativa in Funzioni di Azure
Strumentazione di registrazione azure-monitor-opentelemetry nella distribuzione
Per evitare la generazione di dati duplicati, è possibile disabilitare la registrazione della distribuzione, lasciando abilitata la strumentazione di registrazione nativa in Funzioni di Azure. A tale scopo, impostare la variabile di ambiente OTEL_LOGS_EXPORTER su None.
Dati di telemetria duplicati in Funzioni di Azure "Always On"
Se l'impostazione Always On in Funzioni di Azure è impostata su On, Funzioni di Azure esegue alcuni processi in background al termine di ogni esecuzione. Si supponga, ad esempio, di avere una funzione timer di cinque minuti che chiama configure_azure_monitor ogni volta. Dopo 20 minuti, quattro utilità di esportazione delle metriche potrebbero essere eseguite contemporaneamente. Questa situazione potrebbe essere l'origine dei dati di telemetria delle metriche duplicati.
In una situazione simile, impostare Always On su Off oppure provare ad arrestare manualmente i provider tra ogni chiamata configure_azure_monitor. Per arrestare ciascun provider, eseguire le chiamate di arresto per ogni provider di contatore, traccia e logger correnti, come illustrato nel codice seguente:
Cartelle di lavoro di Azure e Jupyter Notebook potrebbero continuare a eseguire in background i processi dell'utilità di esportazione. Per evitare la generazione di dati di telemetria duplicati, cancellare la cache prima di effettuare altre chiamate a configure_azure_monitor.
Passaggio 4: assicurarsi che i dati della richiesta Flask vengano raccolti
Se si implementa un'applicazione Flask, la raccolta dei dati della tabella Richieste da Application Insights potrebbe non riuscire durante l'uso della libreria client di distribuzione OpenTelemetry di Monitoraggio di Azure per Python. Questo problema si può verificare se le dichiarazioni import non sono strutturate correttamente. Si potrebbe importare il framework dell'applicazione Web flask.Flask prima di chiamare la funzione configure_azure_monitor per strumentare la libreria Flask. Ad esempio, il codice seguente non è in grado di strumentare correttamente l'app Flask:
from azure.monitor.opentelemetry import configure_azure_monitor
from flask import Flask
configure_azure_monitor()
app = Flask(__name__)
È invece consigliabile importare il modulo flask per intero ed effettuare una chiamata a configure_azure_monitor per configurare OpenTelemetry per l'utilizzo di Monitoraggio di Azure prima di accedere a flask.Flask:
from azure.monitor.opentelemetry import configure_azure_monitor
import flask
configure_azure_monitor()
app = flask.Flask(__name__)
In alternativa, è possibile chiamare configure_azure_monitor prima di importare flask.Flask:
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor()
from flask import Flask
app = Flask(__name__)
Supporto tecnico
Selezionare la scheda del linguaggio scelto per scoprire le opzioni di supporto.
Presto disponibile: Nel corso del 2024 verranno gradualmente disattivati i problemi di GitHub come meccanismo di feedback per il contenuto e ciò verrà sostituito con un nuovo sistema di feedback. Per altre informazioni, vedere https://aka.ms/ContentUserFeedback.