Questa guida fornisce istruzioni sull'integrazione e la personalizzazione della strumentazione OpenTelemetry (OTel) in Azure Monitor Application Insights.
Per altre informazioni sui concetti relativi a OpenTelemetry, vedere panoramica di OpenTelemetry o Domande frequenti su OpenTelemetry.
Raccolta dati automatica
Le distribuzioni raccolgono automaticamente i dati raggruppando librerie di strumentazione OpenTelemetry.
Librerie di strumentazione incluse
Richieste
Dipendenze
Registrazione
Per ridurre o aumentare il numero di log inviati a Monitoraggio di Azure, configurare la registrazione per impostare il livello di log appropriato o applicare filtri. Ad esempio, è possibile scegliere di inviare solo Warning e Error log a OpenTelemetry/Azure Monitor. OpenTelemetry non controlla il routing o il filtro dei log. La ILogger configurazione prende queste decisioni. Per altre informazioni sulla configurazione di ILogger, vedere Configurare la registrazione.
Per altre informazioni su ILogger, vedere Registrazione in C# e .NET ed esempi di codice.
L'utilità di esportazione di Monitoraggio di Azure non include librerie di strumentazione.
È possibile raccogliere le dipendenze dagli SDK (Software Development Kit) di Azure utilizzando il seguente esempio di codice per sottoscrivere manualmente la sorgente.
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
// The following line subscribes to dependencies emitted from Azure SDKs
.AddSource("Azure.*")
.AddAzureMonitorTraceExporter()
.AddHttpClientInstrumentation(o => o.FilterHttpRequestMessage = (_) =>
{
// Azure SDKs create their own client span before calling the service using HttpClient
// In this case, we would see two spans corresponding to the same operation
// 1) created by Azure SDK 2) created by HttpClient
// To prevent this duplication we are filtering the span from HttpClient
// as span from Azure SDK contains all relevant information needed.
var parentActivity = Activity.Current?.Parent;
if (parentActivity != null && parentActivity.Source.Name.Equals("Azure.Core.Http"))
{
return false;
}
return true;
})
.Build();
Per ridurre o aumentare il numero di log inviati a Monitoraggio di Azure, configurare la registrazione per impostare il livello di log appropriato o applicare filtri. Ad esempio, è possibile scegliere di inviare solo Warning e Error log a OpenTelemetry/Azure Monitor. OpenTelemetry non controlla il routing o il filtro dei log. La ILogger configurazione prende queste decisioni. Per altre informazioni sulla configurazione di ILogger, vedere Configurare la registrazione.
Richieste
- Consumer di JMS (Java Message Service)
- Consumer Kafka
- Netty
- Quarzo
- RabbitMQ (un servizio di messaggistica open-source)
- Servlet
- Pianificazione Spring
Nota
La strumentazione automatica di Servlet e Netty copre la maggior parte dei servizi HTTP Java, tra cui Java EE, Jakarta EE, Spring Boot, Quarkus e Micronaut.
Dipendenze (più propagazione di traccia distribuita downstream)
- Apache HttpClient
- Apache HttpAsyncClient
- AsyncHttpClient
- Google HttpClient
- gRPC
- java.net.HttpURLConnection
- Java 11 HttpClient
- Client JAX-RS
- Client HTTP di Jetty
- Java Message Service (JMS)
- Kafka
- Client Netty
- OkHttp
- RabbitMQ (un servizio di messaggistica open-source)
Dipendenze (senza propagazione di traccia distribuita downstream)
- Supporta Cassandra
- Supporta Java Database Connectivity (JDBC)
- Supporta MongoDB (asincrono e sincronizzazione)
- Supporta Redis (Lattuce e Jedis)
Metriche
- Metriche di Micrometer, incluse le metriche dell'attuatore Spring Boot
- Metriche JMX (Java Management Extensions)
Log
- Logback (incluse le proprietà MDC) ¹
- Log4j (incluse le proprietà MDC/Contesto thread) ¹
- Registrazione di JBoss (incluse le proprietà MDC) ¹
- java.util.logging ¹
Per ridurre o aumentare il numero di log raccolti da Monitoraggio di Azure, impostare innanzitutto il livello di registrazione desiderato ( ad esempio WARNING o ERROR) nella libreria di registrazione dell'applicazione.
Raccolta predefinita
I dati di telemetria generati dai seguenti SDK di Azure vengono raccolti automaticamente per impostazione predefinita:
[//]: # "Azure Cosmos DB 4.22.0+ due to https://github.com/Azure/azure-sdk-for-java/pull/25571"
[//]: # "the remaining above names and links scraped from https://azure.github.io/azure-sdk/releases/latest/java.html"
[//]: # "and version synched manually against the oldest version in maven central built on azure-core 1.14.0"
[//]: # ""
[//]: # "var table = document.querySelector('#tg-sb-content > div > table')"
[//]: # "var str = ''"
[//]: # "for (var i = 1, row; row = table.rows[i]; i++) {"
[//]: # " var name = row.cells[0].getElementsByTagName('div')[0].textContent.trim()"
[//]: # " var stableRow = row.cells[1]"
[//]: # " var versionBadge = stableRow.querySelector('.badge')"
[//]: # " if (!versionBadge) {"
[//]: # " continue"
[//]: # " }"
[//]: # " var version = versionBadge.textContent.trim()"
[//]: # " var link = stableRow.querySelectorAll('a')[2].href"
[//]: # " str += '* [' + name + '](' + link + ') ' + version + '\n'"
[//]: # "}"
[//]: # "console.log(str)"
Richieste di applicazioni native Spring Boot
- Spring Web
- Spring Web MVC (Model-View-Controller)
- Spring WebFlux
Dipendenze per le applicazioni native Spring Boot
Metriche
Log per le applicazioni native Spring Boot
Per ridurre o aumentare il numero di log raccolti da Monitoraggio di Azure, impostare innanzitutto il livello di registrazione desiderato ( ad esempio WARNING o ERROR) nella libreria di registrazione dell'applicazione.
Per le applicazioni native di Quarkus, vedere la documentazione di Quarkus.
Le seguenti librerie di strumentazione OpenTelemetry sono incluse come parte della distribuzione di Application Insights di Azure Monitor. Per altre informazioni, vedere Azure SDK per JavaScript.
Richieste
Dipendenze
Log
Per ridurre o aumentare il numero di log raccolti da Monitoraggio di Azure, impostare innanzitutto il livello di registrazione desiderato ( ad esempio WARNING o ERROR) nella libreria di registrazione dell'applicazione.
Le strumentazioni possono essere configurate usando AzureMonitorOpenTelemetryOptions:
export class BunyanInstrumentationSample {
static async run() {
// Dynamically import Azure Monitor and Bunyan
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const bunyanMod = await import("bunyan");
const bunyan = (bunyanMod as any).default ?? bunyanMod;
// Enable Azure Monitor integration and bunyan instrumentation
const options = {
instrumentationOptions: {
bunyan: { enabled: true },
},
};
const monitor = useAzureMonitor(options);
// Emit a test log entry
const log = (bunyan as any).createLogger({ name: "testApp" });
log.info(
{
testAttribute1: "testValue1",
testAttribute2: "testValue2",
testAttribute3: "testValue3",
},
"testEvent"
);
console.log("Bunyan log emitted");
}
}
Richieste
Dipendenze
Log
Per ridurre o aumentare il numero di log raccolti da Monitoraggio di Azure, impostare innanzitutto il livello di registrazione desiderato ( ad esempio WARNING o ERROR) nella libreria di registrazione dell'applicazione.
Esempi di uso della libreria di registrazione Python sono disponibili in GitHub.
I dati di telemetria generati da Azure Software Development Kit (SDK) vengono raccolti automaticamente per impostazione predefinita.
Note a piè di pagina
- ¹: supporta la creazione automatica di report di eccezioni non gestite/non rilevate
- ²: supporta le metriche OpenTelemetry
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.
È 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 suggerirne uno per una distribuzione, pubblicare o votare a favore utilizzando i commenti e suggerimenti della community. Essere consapevoli che alcune si basano sulle specifiche sperimentali di OpenTelemetry e potrebbero introdurre modifiche di rilievo nel futuro.
Per aggiungere una libreria della community, usare i metodi ConfigureOpenTelemetryMeterProvider o ConfigureOpenTelemetryTracerProvider dopo aver aggiunto il pacchetto NuGet per la libreria.
Ecco un esempio che dimostra come aggiungere la strumentazione di runtime per raccogliere ulteriori metriche:
dotnet add package OpenTelemetry.Instrumentation.Runtime
// 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();
Ecco un esempio che dimostra come aggiungere la strumentazione di runtime per raccogliere ulteriori metriche:
// 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.
export class RegisterExpressInstrumentationSample {
static async run() {
// Dynamically import Azure Monitor and Express instrumentation
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { registerInstrumentations } = await import("@opentelemetry/instrumentation");
const { ExpressInstrumentation } = await import("@opentelemetry/instrumentation-express");
// Initialize Azure Monitor (uses env var if set)
const monitor = useAzureMonitor();
// Register the Express instrumentation
registerInstrumentations({
instrumentations: [new ExpressInstrumentation()],
});
console.log("Express instrumentation registered");
}
}
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
La strumentazione manuale di una libreria di strumentazione supportata con instrument() e la distribuzione configure_azure_monitor() non è consigliata. Non è uno scenario supportato e si potrebbe ottenere 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())
Rilevatori di risorse
I rilevatori di risorse individuano i metadati dell'ambiente all'avvio e popolano gli attributi delle risorse OpenTelemetry, service.namead esempio , cloud.providere cloud.resource_id. Questi metadati supportano esperienze in Application Insights, ad esempio Mappa applicazioni e collegamento dei servizi di calcolo, e migliorano la correlazione tra tracce, metriche e log.
Suggerimento
Gli attributi delle risorse descrivono il processo e il relativo ambiente. Gli attributi span descrivono una singola operazione. Usare gli attributi delle risorse per le proprietà a livello di app, ad esempio service.name.
Ambienti supportati
| Ambiente |
Funzionamento del rilevamento |
Note |
| Servizio app di Azure |
L'SDK del linguaggio o la distribuzione di Monitoraggio di Azure legge le variabili di ambiente note di Servizio app e i metadati dell'host |
Funziona con .NET, Java, Node.jse Python quando si usano le linee guida in questo articolo. |
| Azure Functions |
Vedere la procedura OpenTelemetry per Funzioni di Azure |
Tutte le linee guida su Azure Functions si trovano lì. |
| Macchine virtuali di Azure |
Lo SDK del linguaggio o la distribuzione esegue una query sul servizio metadati dell'istanza di Azure. |
Verificare che la macchina virtuale abbia accesso all'endpoint del servizio metadati dell'istanza. |
| Il Servizio Azure Kubernetes (AKS) |
Usare il processore dell'agente di raccolta k8sattributes OpenTelemetry per aggiungere metadati Kubernetes |
Consigliato per tutti i linguaggi in esecuzione nel servizio Azure Kubernetes. |
| App contenitore di Azure |
I rilevatori eseguono il mapping delle variabili di ambiente e degli identificatori di risorsa, se disponibili |
È anche possibile impostare OTEL_RESOURCE_ATTRIBUTES per riempire le lacune. |
Strumentazione manuale e automatica
La strumentazione automatica e le distribuzioni di Monitoraggio di Azure abilitano il rilevamento delle risorse quando sono in esecuzione in ambienti di Azure in cui è supportato.
Per le configurazioni manuali, è possibile impostare gli attributi delle risorse direttamente con le opzioni OpenTelemetry standard:
# Applies to .NET (ASP.NET/ASP.NET Core), Java, Node.js, and Python
export OTEL_SERVICE_NAME="my-service"
export OTEL_RESOURCE_ATTRIBUTES="cloud.provider=azure,cloud.region=westus,cloud.resource_id=/subscriptions/<SUB>/resourceGroups/<RG>/providers/Microsoft.Web/sites/<APP>"
In Windows PowerShell:
$Env:OTEL_SERVICE_NAME="my-service"
$Env:OTEL_RESOURCE_ATTRIBUTES="cloud.provider=azure,cloud.region=westus,cloud.resource_id=/subscriptions/<SUB>/resourceGroups/<RG>/providers/Microsoft.Web/sites/<APP>"
Considerazioni sull'ingestione OTLP
- Application Insights usa
service.name per derivare il nome del ruolo cloud. Scegliere un nome stabile per servizio per evitare nodi frammentati nella mappa delle applicazioni.
-
cloud.resource_id migliora il collegamento di calcolo alle risorse di Azure. Se questo attributo non è presente, alcune esperienze potrebbero non mostrare la risorsa di Azure che ha prodotto i dati.
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
-
API Classica di Application Insights
La tabella seguente rappresenta i tipi di telemetria personalizzati attualmente supportati:
| Lingua |
Eventi personalizzati |
Metriche personalizzate |
Dipendenze |
Eccezioni |
Visualizzazioni pagina |
Requests |
Traces |
|
ASP.NET Core |
|
|
|
|
|
|
|
| API OpenTelemetry |
|
Sì |
Sì |
Sì |
|
Sì |
|
API ILogger |
|
|
|
|
|
|
Sì |
| API IA classica |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Giava |
|
|
|
|
|
|
|
| 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ì |
|
|
|
|
|
|
|
|
|
|
Pitone |
|
|
|
|
|
|
|
| API OpenTelemetry |
|
Sì |
Sì |
Sì |
|
Sì |
|
| Modulo di registrazione Python |
|
|
|
|
|
|
Sì |
| Estensione eventi |
Sì |
|
|
|
|
|
Sì |
Nota
Application Insights Java 3.x e Application Insights Node.js 3.x raccolgono i dati di telemetria dall'API classica di Application Insights. Questo comportamento semplifica gli aggiornamenti e supporta temporaneamente i dati di telemetria personalizzati fino a quando l'API OpenTelemetry include tutti i tipi di telemetria personalizzati.
Aggiungere le metriche personalizzate
In questo contesto, il termine delle metriche personalizzate si riferisce alla strumentazione manuale del codice per raccogliere metriche aggiuntive oltre a quanto raccolto automaticamente dalle librerie di strumentazione OpenTelemetry. Per altre informazioni sull'uso delle metriche, vedere Metriche in Application Insights.
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 di OpenTelemetry Metric Instruments.
| Strumento OpenTelemetry |
Tipo di aggregazione di Monitoraggio di Azure |
| Contatore |
Somma |
| Contatore asincrono |
Somma |
| Istogramma |
Min, Max, Media, Somma e Numero |
| Misuratore asincrono |
Media |
| UpDownCounter |
Somma |
| UpDownCounter asincrono |
Somma |
Attenzione
Altri tipi di aggregazione non sono significativi nella maggior parte dei casi.
La specifica OpenTelemetry descrive gli strumenti e fornisce esempi di quando è possibile usare ognuno di essi.
Suggerimento
L'istogramma è il più versatile e più strettamente equivalente all'API getMetric classica 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 versatile, altri strumenti OpenTelemetry hanno un effetto minore sulle prestazioni dell'applicazione.
Esempio di istogramma
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);
}
}
Inserimento di OpenTelemetry:
Creare un istogramma:
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);
export class HistogramSample {
static async run() {
// Dynamically import Azure Monitor and metrics API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a histogram and record values
const meter = metrics.getMeter("testMeter");
const histogram = meter.createHistogram("histogram");
histogram.record(1, { testKey: "testValue" });
histogram.record(30, { testKey: "testValue2" });
histogram.record(100, { testKey2: "testValue" });
console.log("Histogram metrics recorded");
}
}
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
import os
# 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>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# 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()
Controesempio
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"));
}
}
Inserimento di OpenTelemetry:
Creare il contatore:
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.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"));
export class CounterSample {
static async run() {
// Dynamically import Azure Monitor and metrics API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a counter and add some sample values
const meter = metrics.getMeter("otel_azure_monitor_counter_demo");
const counter = meter.createCounter("MyFruitCounter");
counter.add(1, { name: "apple", color: "red" });
counter.add(2, { name: "lemon", color: "yellow" });
counter.add(1, { name: "lemon", color: "yellow" });
counter.add(2, { name: "apple", color: "green" });
counter.add(5, { name: "apple", color: "red" });
counter.add(4, { name: "lemon", color: "yellow" });
console.log("Counter metrics recorded");
}
}
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
import os
# 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>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# 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()
Esempio di misuratore
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"));
});
}
}
Inserimento di OpenTelemetry:
Creare un misuratore:
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.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"));
});
export class GaugeSample {
static async run() {
// Dynamically import Azure Monitor and metrics API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create an observable gauge and register a callback
const meter = metrics.getMeter("testMeter");
const gauge = meter.createObservableGauge("gauge");
gauge.addCallback((observableResult) => {
const randomNumber = Math.floor(Math.random() * 100);
observableResult.observe(randomNumber, { testKey: "testValue" });
});
console.log("Observable gauge registered");
}
}
# Import the necessary packages.
from typing import Iterable
import os
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>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# 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, potresti voler segnalare manualmente le eccezioni oltre a quelle che riportano le 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.
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(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:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Impostare lo stato su error e registrare un'eccezione nel codice:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
Impostare lo stato su error e registrare un'eccezione nel codice:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
L'SDK di Node.js esporta eccezioni basate su intervalli registrati manualmente in Application Insights come eccezioni solo se registrate in un intervallo di livello superiore o figlio di un intervallo remoto o interno.
export class CustomExceptionSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a span and record an exception
const tracer = trace.getTracer("testTracer");
const span = tracer.startSpan("hello");
try {
throw new Error("Test Error");
} catch (error) {
span.recordException(error as Error);
} finally {
span.end();
}
console.log("Exception recorded on span");
}
}
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 segmento nella visualizzazione delle transazioni end-to-end.
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(). È dovuto al fatto che parti dell'API di traccia OpenTelemetry vengono incorporate direttamente nel runtime .NET. Per altre informazioni, vedere Introduzione all'API di tracing di OpenTelemetry .NET.
// 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(). È dovuto al fatto che parti dell'API di traccia OpenTelemetry vengono incorporate direttamente nel runtime .NET. Per altre informazioni, vedere Introduzione all'API di tracing di OpenTelemetry .NET.
// 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:
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-annotations</artifactId>
<version>1.32.0</version>
</dependency>
Usare l'annotazione @WithSpan per generare un intervallo ogni volta che viene eseguito il metodo:
import io.opentelemetry.instrumentation.annotations.WithSpan;
@WithSpan(value = "your span name")
public void yourMethod() {
}
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:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Usare la classe GlobalOpenTelemetry per creare un Tracer:
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = GlobalOpenTelemetry.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();
}
Inserimento di OpenTelemetry:
Creare un Tracer:
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();
}
export class CustomTraceSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a custom span, add attributes/events, then end
const tracer = trace.getTracer("otel_azure_monitor_custom_trace_demo");
const span = tracer.startSpan("doWork");
try {
span.setAttribute("component", "worker");
span.setAttribute("operation.id", "42");
span.addEvent("invoking doWork");
for (let i = 0; i < 1_000_000; i++) { /* simulate work */ }
} catch (err) {
span.recordException(err as Error);
} finally {
span.end();
}
console.log("Custom span recorded");
}
}
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 eventi personalizzati
Application Insights archivia eventi personalizzati nella customEvents tabella. Un modo per analizzare, filtrare e visualizzarli consiste nell'usare le esperienze di utilizzo di Application Insights.
Se si vuole automatizzare la raccolta di eventi di interazione lato client, è possibile usare il plug-in in JavaScript SDK.
Gli eventi personalizzati sono disponibili in anteprima pubblica e utilizzano Azure.Monitor.OpenTelemetry.AspNetCore 1.3.0-beta.3.
Per inviare un CustomEvent utilizzando ILogger, impostare l'attributo "microsoft.custom_event.name" nel modello di messaggio.
// Create a logger factory and configure OpenTelemetry with Azure Monitor
var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter();
});
});
// Create a logger for the specified category
var logger = loggerFactory.CreateLogger(logCategoryName);
// Log a custom event with a custom name and additional attribute
// The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}", "test-event-name", "val1");
Gli eventi personalizzati sono in anteprima pubblica e usano Azure.Monitor.OpenTelemetry.Exporter 1.4.0-beta.3.
Per inviare un CustomEvent utilizzando ILogger, impostare l'attributo "microsoft.custom_event.name" nel modello di messaggio.
// Create a logger factory and configure OpenTelemetry with Azure Monitor
var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter();
});
});
// Create a logger for the specified category
var logger = loggerFactory.CreateLogger(logCategoryName);
// Log a custom event with a custom name and additional attribute
// The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}", "test-event-name", "val1");
Per inviare un customEvent con l'agente Java, impostare l'attributo "microsoft.custom_event.name" nel record di log di OpenTelemetry.
A seconda che l'agente Java di Application Insights sia in uso o l'SDK di configurazione automatica, il modo di recuperare il logger OpenTelemetry è leggermente diverso. Questo dettaglio è illustrato più avanti negli esempi seguenti.
Per l'agente Java di Application Insights:
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.logs.Logger;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.logs.Severity;
Logger logger = GlobalOpenTelemetry.get().getLogsBridge().get("opentelemetry-logger");
logger.logRecordBuilder()
.setAttribute(AttributeKey.stringKey("microsoft.custom_event.name"),"test-event-name")
.setSeverity(Severity.INFO)
.emit();
Per l'SDK di configurazione automatica:
import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigure;
import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigureOptions;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.logs.Logger;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder;
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorAutoConfigureOptions options = new AzureMonitorAutoConfigureOptions();
options.connectionString("<your connection string>");
AzureMonitorAutoConfigure.customize(sdkBuilder, options);
OpenTelemetry openTelemetry = sdkBuilder.build().getOpenTelemetrySdk();
Logger logger = openTelemetry.getLogsBridge().get("opentelemetry-logger");
logger.logRecordBuilder()
.setAttribute(AttributeKey.stringKey("microsoft.custom_event.name"),"test-event-name")
.setSeverity(Severity.INFO)
.emit();
Per generare eventi personalizzati in modo affidabile, usare direttamente l'API OpenTelemetry. Alcuni framework di registrazione non supportano l'aggiunta o l'analisi dell'attributo degli eventi personalizzati.
Non è possibile inviare un customEvent oggetto usando l'attributo "microsoft.custom_event.name" in Java nativo.
Per inviare un customEvent utilizzando logger.emit, impostare l'attributo "microsoft.custom_event.name" nell'oggetto log attributes. È anche possibile includere altri attributi in base alle esigenze.
export class CustomEventSample {
static async run() {
// Dynamically import Azure Monitor and the OpenTelemetry logs API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { logs, SeverityNumber } = await import("@opentelemetry/api-logs");
// Initialize Azure Monitor (enables logs bridge)
const monitor = useAzureMonitor();
// Get a logger and emit a customEvent by setting the microsoft attribute key
const logger = logs.getLogger("my-app-logger");
logger.emit({
body: "Hello World!",
severityNumber: SeverityNumber.INFO,
attributes: {
"microsoft.custom_event.name": "test-event-name",
"additional_attrs": "val1",
},
});
// Example: populate client_IP via attribute 'client.address'
logger.emit({
body: "This entry will have a custom client_IP",
severityNumber: SeverityNumber.INFO,
attributes: {
"microsoft.custom_event.name": "test_event",
"client.address": "192.168.1.1",
},
});
console.log("Custom events emitted");
}
}
Per inviare un customEvent in Python, utilizzare la libreria logging con l'attributo "microsoft.custom_event.name" nel parametro extra.
import logging
from azure.monitor.opentelemetry import configure_azure_monitor
# Set up your application logger
logger = logging.getLogger("my-app-logger")
# Configure Azure Monitor to collect logs from the specified logger name
configure_azure_monitor(
logger_name="my-app-logger", # Collect logs from your namespaced logger
)
# Log a custom event with a custom name and additional attribute
# The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.warning(
"Hello World!",
extra={
"microsoft.custom_event.name": "test-event-name",
"additional_attrs": "val1"
}
)
# You can also populate fields like client_IP with attribute `client.address`
logger.info(
"This entry will have a custom client_IP",
extra={
"microsoft.custom_event.name": "test_event",
"client.address": "192.168.1.1"
}
)
Modificare la telemetria
Questa sezione illustra come modificare i dati di telemetria.
Aggiungere attributi span
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 Span
Tutti gli attributi aggiunti agli intervalli vengono esportati come proprietà personalizzate. Popolano il campo customDimensions nella tabella richieste, dipendenze, tracce o eccezioni.
Per aggiungere attributi di span, usare uno dei seguenti due modi:
Suggerimento
Il vantaggio di usare le opzioni fornite dalle librerie di strumentazione, quando sono disponibili, è che l'intero contesto sia disponibile. Di conseguenza, gli utenti possono effettuare una selezione per aggiungere o filtrare altri attributi. Ad esempio, l'opzione enrich nella libreria di strumentazione HttpClient consente agli utenti di accedere a HttpRequestMessage e a HttpResponseMessage stesso. 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:
Usare un processore personalizzato:
Suggerimento
Aggiungere il processore illustrato qui prima di aggiungere Azure Monitor.
// 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 di span, usare uno dei seguenti due modi:
- 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, è che l'intero contesto sia disponibile. Di conseguenza, gli utenti possono effettuare una selezione per aggiungere o filtrare altri attributi. Ad esempio, l'opzione enrich 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:
Usare un processore personalizzato:
Suggerimento
Aggiungere il processore illustrato di seguito prima dell'Exporter di Azure Monitor.
// 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 di intervallo popola il campo customDimensions della tabella requests, dependencies, traces o exceptions.
Aggiungere opentelemetry-api-1.0.0.jar (o versione successiva) all'applicazione:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Aggiungere dimensioni personalizzate nel codice:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
Aggiungere dimensioni personalizzate nel codice:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
export class SpanAttributeEnrichmentSample {
static async run() {
// Dynamically import the Azure Monitor integration
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
// Create a SpanEnrichingProcessor to add custom dimensions
class SpanEnrichingProcessor {
forceFlush() { return Promise.resolve(); }
shutdown() { return Promise.resolve(); }
onStart() {}
onEnd(span: any) {
(span as any).attributes = (span as any).attributes || {};
(span as any).attributes["CustomDimension1"] = "value1";
(span as any).attributes["CustomDimension2"] = "value2";
}
}
// Initialize Azure Monitor with the custom processor
const monitor = useAzureMonitor({
spanProcessors: [new SpanEnrichingProcessor()],
});
console.log("Span enrichment processor registered");
}
}
Usare un processore personalizzato:
...
# 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 per le richieste impostando un attributo sull'intervallo. Application Insights usa l'indirizzo IP per generare gli attributi di posizione utente e quindi lo rimuove per impostazione predefinita.
Usare l'esempio di proprietà personalizzata, ma sostituire le righe di codice seguenti in ActivityEnrichingProcessor.cs:
// 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>");
Usare l'esempio di proprietà personalizzata, ma sostituire le righe di codice seguenti in ActivityEnrichingProcessor.cs:
// 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>");
Java popola automaticamente questo campo.
Questo campo viene popolato automaticamente.
Usare l'esempio di proprietà personalizzata, ma sostituire le righe di codice seguenti:
export class SetUserIpSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor();
// Framework-agnostic helper to set client IP on the active server span
const setIpForRequest = (clientIp: string) => {
const span = trace.getActiveSpan();
if (span) {
// Preferred attribute for client IP
span.setAttribute("client.address", clientIp);
// Optional: legacy/alternate attribute
span.setAttribute("http.client_ip", clientIp);
}
};
// Call setIpForRequest("<IP Address>") from within your web framework's request pipeline
console.log("Use setIpForRequest('<IP Address>') inside your request handler to stamp the active span.");
}
}
Usare l'esempio di proprietà personalizzata, ma sostituire le righe di codice seguenti in SpanEnrichingProcessor.py:
# 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.
Usare l'esempio di proprietà personalizzata:
// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<User Id>");
Usare l'esempio di proprietà personalizzata:
// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<User Id>");
Popolare il campo user ID della tabella requests, dependencies o exceptions.
Aggiungere opentelemetry-api-1.0.0.jar (o versione successiva) all'applicazione:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Impostare user_Id nel codice:
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser"); // (user_AuthenticatedId)
Span.current().setAttribute("enduser.pseudo.id", "myuser"); // (user_Id)
Popolare il campo user ID della tabella requests, dependencies o exceptions.
Impostare user_Id nel codice:
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser"); // (user_AuthenticatedId)
Span.current().setAttribute("enduser.pseudo.id", "myuser"); // (user_Id)
Usare l'esempio di proprietà personalizzata, ma sostituire le righe di codice seguenti:
export class SetUserIdSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor();
// Framework-agnostic helper to set user identifiers on the active server span
const setUserForRequest = (authenticatedId?: string, anonymousId?: string) => {
const span = trace.getActiveSpan();
if (span) {
if (authenticatedId) span.setAttribute("enduser.id", authenticatedId); // user_AuthenticatedId
if (anonymousId) span.setAttribute("enduser.pseudo.id", anonymousId); // user_Id
}
};
// Call setUserForRequest("<authenticated-id>", "<anonymous-id>") inside your request handler
console.log("Use setUserForRequest('<auth-id>', '<anon-id>') inside your request handler to stamp the active span.");
}
}
Usare l'esempio di proprietà personalizzata, ma sostituire le righe di codice seguenti:
# Set the `enduser.id` attribute of the span to the specified user ID.
span._attributes["enduser.id"] = "<User ID>"
Aggiungere attributi di log
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 instrumentati automaticamente. Il collegamento di dimensioni personalizzate ai log può essere eseguito in questi modi:
Per le applicazioni native Spring Boot, Logback è instrumentato automaticamente.
export class BunyanLogAttributesSample {
static async run() {
// Dynamically import Azure Monitor and Bunyan
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const bunyanMod = await import("bunyan");
const bunyan = (bunyanMod as any).default ?? bunyanMod;
// Enable Azure Monitor integration and bunyan instrumentation
const monitor = useAzureMonitor({
instrumentationOptions: { bunyan: { enabled: true } },
});
// Emit a log with custom attributes
const log = (bunyan as any).createLogger({ name: "testApp" });
log.info({ key1: "value1", feature: "demo" }, "Warning log with properties");
console.log("Bunyan log with attributes emitted");
}
}
La libreria di registrazione Python viene strumentata automaticamente. È possibile allegare dimensioni personalizzate ai log inserendo 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"})
...
Ottenere l'ID di traccia o l'ID intervallo
È possibile ottenere il Trace ID e il Span ID dello Span attualmente attivo seguendo i passaggi seguenti.
Nota
Le classi Activity e ActivitySource dello spazio dei nomi System.Diagnostics rappresentano rispettivamente i concetti OpenTelemetry di Span e Tracer. È dovuto al fatto che parti dell'API di traccia OpenTelemetry vengono incorporate direttamente nel runtime .NET. Per altre informazioni, vedere Introduzione all'API di tracing di OpenTelemetry .NET.
// 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. È dovuto al fatto che parti dell'API di traccia OpenTelemetry vengono incorporate direttamente nel runtime .NET. Per altre informazioni, vedere Introduzione all'API di tracing di OpenTelemetry .NET.
// 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 di span.
Aggiungere opentelemetry-api-1.0.0.jar (o versione successiva) all'applicazione:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Ottenere l'ID di traccia della richiesta e l'ID intervallo nel codice:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
Ottenere l'ID di traccia della richiesta e l'ID intervallo nel codice:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
Ottenere l'ID di traccia della richiesta e l'ID intervallo nel codice:
export class GetTraceAndSpanIdSample {
static async run() {
// Dynamically import tracing API
const { trace } = await import("@opentelemetry/api");
// Read the span/trace id from the active span (if any)
const activeSpan = trace.getActiveSpan();
const spanId = activeSpan?.spanContext().spanId;
const traceId = activeSpan?.spanContext().traceId;
console.log("SpanId:", spanId, "TraceId:", 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
Passaggi successivi
- Per configurare ulteriormente la distribuzione di OpenTelemetry, vedere Configurazione di OpenTelemetry di Azure Monitor.
- Per esaminare il codice sorgente, vedere il repository GitHub Azure Monitor AspNetCore.
- Per installare il pacchetto NuGet, verificare la disponibilità di aggiornamenti o visualizzare le note sulla versione, vedere la pagina del pacchetto NuGet Azure Monitor AspNetCore.
- Per acquisire familiarità con Monitoraggio di Azure e OpenTelemetry, vedere l'applicazione di esempio di Monitoraggio di Azure.
- Per altre informazioni su OpenTelemetry e sulla relativa community, vedere il repository GitHub OpenTelemetry .NET.
- Per abilitare le esperienze di utilizzo, abilitare il monitoraggio degli utenti del Web o del browser.
- Per esaminare le domande frequenti, i passaggi per la risoluzione dei problemi, le opzioni di supporto o per fornire commenti e suggerimenti su OpenTelemetry, vedere La Guida, il supporto e il feedback di OpenTelemetry per Application Insights di Monitoraggio di Azure.
- Per configurare ulteriormente la distribuzione di OpenTelemetry, vedere la configurazione di OpenTelemetry per Azure Monitor.
- Per esaminare il codice sorgente, vedere il repository GitHub dell'utilità di esportazione di Monitoraggio di Azure.
- Per installare il pacchetto NuGet, verificare la disponibilità di aggiornamenti o consultare le note di rilascio, vedere la pagina Pacchetto NuGet Azure Monitor Exporter.
- Per acquisire familiarità con Monitoraggio di Azure e OpenTelemetry, vedere l'applicazione di esempio di Monitoraggio di Azure.
- Per altre informazioni su OpenTelemetry e sulla relativa community, vedere il repository GitHub OpenTelemetry .NET.
- Per abilitare le esperienze di utilizzo, abilitare il monitoraggio degli utenti del Web o del browser.
- Per esaminare le domande frequenti, i passaggi per la risoluzione dei problemi, le opzioni di supporto o per fornire commenti e suggerimenti su OpenTelemetry, vedere La Guida, il supporto e il feedback di OpenTelemetry per Application Insights di Monitoraggio di Azure.
- Per esaminare il codice sorgente, vedere il repository GitHub Azure Monitor OpenTelemetry.
- Per installare il pacchetto npm e verificare la disponibilità di aggiornamenti, vedere la
@azure/monitor-opentelemetry pagina del pacchetto npm .
- Per acquisire familiarità con Monitoraggio di Azure, Application Insights e OpenTelemetry, consulta l'applicazione di esempio di Azure Monitor.
- Per altre informazioni su OpenTelemetry e sulla relativa community, vedere il repository GitHub Di OpenTelemetry JavaScript.
- Per abilitare le esperienze di utilizzo, abilitare il monitoraggio degli utenti del Web o del browser.
- Per esaminare le domande frequenti, i passaggi per la risoluzione dei problemi, le opzioni di supporto o per fornire commenti e suggerimenti su OpenTelemetry, vedere La Guida, il supporto e il feedback di OpenTelemetry per Application Insights di Monitoraggio di Azure.
- Per esaminare il codice sorgente e la documentazione aggiuntiva, vedere il repository GitHub Azure Monitor Distro.
- Per visualizzare esempi aggiuntivi e casi d'uso, vedere gli Esempi del Distro di Monitoraggio di Azure.
- Per visualizzare le note sulla versione, vedere le note sulla versione in GitHub.
- Per installare il pacchetto PyPI, verificare la disponibilità di aggiornamenti o visualizzare le note sulla versione, consultare la pagina Azure Monitor Distro PyPI Package.
- Per acquisire familiarità con Monitoraggio di Azure, Application Insights e OpenTelemetry, consulta l'applicazione di esempio di Azure Monitor.
- Per altre informazioni su OpenTelemetry e sulla relativa community, vedere il repository GitHub Di OpenTelemetry Python.
- Per visualizzare le strumentazioni e i componenti OpenTelemetry disponibili, vedere il repository GitHub degli sviluppatori Python di OpenTelemetry.
- Per abilitare le esperienze di utilizzo, abilitare il monitoraggio degli utenti del Web o del browser.
- Per esaminare le domande frequenti, i passaggi per la risoluzione dei problemi, le opzioni di supporto o per fornire commenti e suggerimenti su OpenTelemetry, vedere La Guida, il supporto e il feedback di OpenTelemetry per Application Insights di Monitoraggio di Azure.