Deze handleiding bevat instructies voor het integreren en aanpassen van OTelemetry-instrumentatie (OpenTelemetry) in Azure Monitor Application Insights.
Zie het overzicht van OpenTelemetry of de veelgestelde vragen over OpenTelemetry voor meer informatie over OpenTelemetry-concepten.
Automatische gegevensverzameling
De distributies verzamelen automatisch gegevens door openTelemetry-instrumentatiebibliotheken te bundelen.
Opgenomen instrumentatiebibliotheken
Verzoeken
Afhankelijkheden
Logboekregistratie
Als u het aantal logboeken dat naar Azure Monitor wordt verzonden wilt verminderen of verhogen, configureert u logboekregistratie om het juiste logboekniveau in te stellen of filters toe te passen. U kunt er bijvoorbeeld voor kiezen om alleen Warning- en Error-logs naar OpenTelemetry/Azure Monitor te verzenden. OpenTelemetry beheert geen logboekroutering of -filtering. Uw ILogger configuratie neemt deze beslissingen. Voor meer informatie over het configureren van ILogger, zie Logboekregistratie configureren.
Zie ILogger en codevoorbeelden voor meer informatie.
De Azure Monitor-exporteur bevat geen instrumentatiebibliotheken.
U kunt afhankelijkheden van de Azure Software Development Kits (SDKs) verzamelen met behulp van het volgende codevoorbeeld om u handmatig op de bron te abonneren.
// 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();
Als u het aantal logboeken dat naar Azure Monitor wordt verzonden wilt verminderen of verhogen, configureert u logboekregistratie om het juiste logboekniveau in te stellen of filters toe te passen. U kunt er bijvoorbeeld voor kiezen om alleen Warning- en Error-logs naar OpenTelemetry/Azure Monitor te verzenden. OpenTelemetry beheert geen logboekroutering of -filtering. Uw ILogger configuratie neemt deze beslissingen. Voor meer informatie over het configureren van ILogger, zie Logboekregistratie configureren.
Verzoeken
- JMS-gebruikers (Java Message Service)
- Kafka-consumenten
- Netty
- Kwarts
- RabbitMQ
- Servlets
- Lenteplanning
Notitie
Servlet en Netty autoinstrumentation omvat de meeste Java HTTP-services, waaronder Java EE, Jakarta EE, Spring Boot, Quarkus en Micronaut.
Afhankelijkheden (plus gedistribueerde trace-propagatie stroomafwaarts)
- Apache HttpClient
- Apache HttpAsyncClient
- AsyncHttpClient
- Google HttpClient
- gRPC
- java.net.HttpURLConnection
- Java 11 HttpClient
- JAX-RS-client
- Jetty HttpClient
- JMS (Java Message Service)
- Kafka
- Netty-client
- OkHttp
- RabbitMQ
Afhankelijkheden (zonder downstream gedistribueerde traceringspropagatie)
- Ondersteunt Cassandra
- Ondersteunt Java Database Connectivity (JDBC)
- Ondersteunt MongoDB (asynchroon en synchroniseren)
- Ondersteunt Redis (Lettuce en Jedis)
Statistieken
- Metrische gegevens van micrometer, waaronder metrische gegevens van Spring Boot Actuator
- Metrische gegevens van Java Management Extensions (JMX)
logboeken
- Logback (inclusief MDC-eigenschappen) ¹
- Log4j (inclusief eigenschappen van MDC/Thread Context) ¹
- JBoss Logging (inclusief MDC-eigenschappen) ¹
- java.util.logging ¹
Als u het aantal logboeken dat door Azure Monitor wordt verzameld wilt verminderen of verhogen, stelt u eerst het gewenste logboekregistratieniveau (zoals WARNING of ERROR) in de logboekregistratiebibliotheek van de toepassing in.
Standaardverzameling
Telemetrie die door de volgende Azure SDK's wordt verzonden, wordt standaard automatisch verzameld:
[//]: # "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)"
Aanvragen voor systeemeigen Spring Boot-toepassingen
- Spring Web
- Spring Web MVC (model-View-Controller)
- Spring WebFlux
Afhankelijkheden voor systeemeigen Spring Boot-toepassingen
Statistieken
- Metrische gegevens van Micrometer
Logboeken voor systeemeigen Spring Boot-toepassingen
Als u het aantal logboeken dat door Azure Monitor wordt verzameld wilt verminderen of verhogen, stelt u eerst het gewenste logboekregistratieniveau (zoals WARNING of ERROR) in de logboekregistratiebibliotheek van de toepassing in.
Raadpleeg de quarkus-documentatie voor systeemeigen toepassingen van Quartz.
Notitie
De Quarkus-community ondersteunt en onderhoudt Quarkus-extensies. Gebruik Quarkus community ondersteuningskanalen voor hulp. Microsoft biedt geen technische ondersteuning voor deze integratie.
De volgende OpenTelemetry Instrumentation-bibliotheken zijn opgenomen als onderdeel van de Azure Monitor Application Insights-distributie. Zie Azure SDK voor JavaScript voor meer informatie.
Verzoeken
Afhankelijkheden
logboeken
Als u het aantal logboeken dat door Azure Monitor wordt verzameld wilt verminderen of verhogen, stelt u eerst het gewenste logboekregistratieniveau (zoals WARNING of ERROR) in de logboekregistratiebibliotheek van de toepassing in.
Instrumentaties kunnen worden geconfigureerd met behulp van 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");
}
}
Verzoeken
Afhankelijkheden
logboeken
Als u het aantal logboeken dat door Azure Monitor wordt verzameld wilt verminderen of verhogen, stelt u eerst het gewenste logboekregistratieniveau (zoals WARNING of ERROR) in de logboekregistratiebibliotheek van de toepassing in.
Voorbeelden van het gebruik van de Python-logboekregistratiebibliotheek vindt u op GitHub.
Telemetrie die wordt verzonden door Azure Software Development Kits (SDK's) wordt standaard automatisch verzameld .
Voetnoten
- ¹: Ondersteunt automatische rapportage van niet-verwerkte/niet-opgevangen uitzonderingen
- ²: Ondersteunt metrische gegevens van OpenTelemetry
Aanbeveling
Alle metrische gegevens van OpenTelemetry, ongeacht of deze automatisch worden verzameld uit instrumentatiebibliotheken of handmatig worden verzameld uit aangepaste codering, worden momenteel beschouwd als Application Insights 'aangepaste metrische gegevens' voor factureringsdoeleinden.
Meer informatie.
U kunt automatisch meer gegevens verzamelen wanneer u instrumentatiebibliotheken van de OpenTelemetry-community opneemt.
Let op
We ondersteunen of garanderen de kwaliteit van community-instrumentatiebibliotheken niet. Om er een voor onze distributie voor te stellen, plaats een bericht of stem voor in onze feedbackcommunity. Houd er rekening mee dat sommige zijn gebaseerd op experimentele OpenTelemetry-specificaties en kunnen toekomstige wijzigingen veroorzaken.
Als u een communitybibliotheek wilt toevoegen, gebruikt u de ConfigureOpenTelemetryMeterProvider of ConfigureOpenTelemetryTracerProvider methoden nadat u het NuGet-pakket voor de bibliotheek hebt toegevoegd.
In het volgende voorbeeld ziet u hoe runtime-instrumentatie kan worden toegevoegd om extra metrische gegevens te verzamelen:
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();
In het volgende voorbeeld ziet u hoe runtime-instrumentatie kan worden toegevoegd om extra metrische gegevens te verzamelen:
// 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();
U kunt de Java-distributie niet uitbreiden met community-instrumentatiebibliotheken. Als u wilt aanvragen dat we een andere instrumentatiebibliotheek opnemen, opent u een probleem op onze GitHub-pagina. In de volgende stappen vindt u een koppeling naar onze GitHub-pagina.
U kunt geen community-instrumentatiebibliotheken gebruiken met systeemeigen GraalVM Java-toepassingen.
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");
}
}
Als u een community-instrumentatiebibliotheek wilt toevoegen (niet officieel ondersteund/opgenomen in Azure Monitor-distributie), kunt u rechtstreeks instrumenteren met de instrumentaties. De lijst met community instrumentatiebibliotheken vindt u hier.
Notitie
Het instrumenteren van een ondersteunde instrumentatiebibliotheek handmatig met instrument() en de distributie configure_azure_monitor() wordt niet aanbevolen. Het is een ongesteund scenario en u kunt ongewenst gedrag in uw telemetrie krijgen.
# 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())
Brondetectoren
Resourcedetectoren detecteren omgevingsmetagegevens bij het opstarten en vullen OpenTelemetry-resourcekenmerken zoals service.name, cloud.provideren cloud.resource_id. Deze metagegevens maken gebruik van ervaringen in Application Insights, zoals application map en compute linking, en verbetert de correlatie tussen traceringen, metrische gegevens en logboeken.
Aanbeveling
Resourcekenmerken beschrijven het proces en de bijbehorende omgeving. Span-kenmerken beschrijven één bewerking. Gebruik resourcekenmerken voor eigenschappen op app-niveau, zoals service.name.
Ondersteunde omgevingen
| Milieu |
Hoe detectie werkt |
Opmerkingen |
| Azure App Service |
De taal-SDK of Azure Monitor distro leest bekende App Service-omgevingsvariabelen en hostmetagegevens. |
Werkt met .NET, Java, Node.jsen Python wanneer u de richtlijnen in dit artikel gebruikt. |
| Azure Functions (serverloze computerdiensten van Azure) |
Zie de Azure Functions OpenTelemetry-handleiding |
Alle Azure Functions-richtlijnen bevinden zich daar. |
| Azure Virtual Machines |
De taal-SDK of distributie voert query's uit op de Azure Instance Metadata Service |
Zorg ervoor dat de VIRTUELE machine toegang heeft tot het eindpunt van de instantiemetagegevensservice. |
| Azure Kubernetes Service (AKS) |
De OpenTelemetry Collector-processor k8sattributes gebruiken om Kubernetes-metagegevens toe te voegen |
Aanbevolen voor alle talen die in AKS draaien. |
| Azure Container Apps - een dienst van Microsoft waarmee je containers kunt uitvoeren en beheren in de cloud. |
Detectors brengen omgevingsvariabelen en resource-id's in kaart wanneer deze beschikbaar zijn |
U kunt ook OTEL_RESOURCE_ATTRIBUTES instellen om hiaten op te vullen. |
Handmatige en automatische instrumentatie
Automatische instrumentatie en de Azure Monitor-distributies maken detectie van resources mogelijk wanneer ze worden uitgevoerd in Azure-omgevingen waarvoor ondersteuning wordt geboden.
Voor handmatige instellingen kunt u resourcekenmerken rechtstreeks instellen met standaardOpties voor OpenTelemetry:
# 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>"
Overwegingen voor OTLP-gegevensinname
- Application Insights gebruikt
service.name om de naam van de cloudrol af te leiden. Kies een stabiele naam per service om gefragmenteerde knooppunten in toepassingsoverzicht te voorkomen.
-
cloud.resource_id verbetert de rekenkrachtkoppeling naar Azure-resources. Als dit kenmerk ontbreekt, worden in sommige ervaringen mogelijk niet de Azure-resource weergegeven die de gegevens heeft geproduceerd.
Aangepaste telemetrie verzamelen
In deze sectie wordt uitgelegd hoe u aangepaste telemetriegegevens van uw toepassing verzamelt.
Afhankelijk van uw taal en signaaltype zijn er verschillende manieren om aangepaste telemetrie te verzamelen, waaronder:
- OpenTelemetry-API
- Taalspecifieke bibliotheken voor logboekregistratie/metrische gegevens
- Klassieke Application Insights-API
De volgende tabel vertegenwoordigt de momenteel ondersteunde aangepaste telemetrietypen:
| Taal |
Aangepaste gebeurtenissen |
Aangepaste metrische gegevens |
Afhankelijkheden |
Uitzonderingen |
Paginaweergaven |
Verzoeken |
Traceringen |
|
ASP.NET Core |
|
|
|
|
|
|
|
| OpenTelemetry-API |
|
Ja |
Ja |
Ja |
|
Ja |
|
ILogger API |
|
|
|
|
|
|
Ja |
| KLASSIEKE AI-API |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Java |
|
|
|
|
|
|
|
| OpenTelemetry-API |
|
Ja |
Ja |
Ja |
|
Ja |
|
Logback, Log4j, jul. |
|
|
|
Ja |
|
|
Ja |
| Metrische gegevens van Micrometer |
|
Ja |
|
|
|
|
|
| KLASSIEKE AI-API |
Ja |
Ja |
Ja |
Ja |
Ja |
Ja |
Ja |
|
|
|
|
|
|
|
|
|
Node.js |
|
|
|
|
|
|
|
| OpenTelemetry-API |
|
Ja |
Ja |
Ja |
|
Ja |
|
|
|
|
|
|
|
|
|
|
Python |
|
|
|
|
|
|
|
| OpenTelemetry-API |
|
Ja |
Ja |
Ja |
|
Ja |
|
| Module voor python-logboekregistratie |
|
|
|
|
|
|
Ja |
| Extensie voor gebeurtenissen |
Ja |
|
|
|
|
|
Ja |
Notitie
Application Insights Java 3.x en Application Insights Node.js 3.x verzamelen telemetrie van de klassieke Application Insights-API. Dit gedrag vereenvoudigt upgrades en ondersteunt tijdelijk aangepaste telemetrie totdat de OpenTelemetry-API alle aangepaste telemetrietypen bevat.
Aangepaste metrische gegevens toevoegen
In deze context verwijst de term voor aangepaste metrische gegevens naar het handmatig instrumenteren van uw code om extra metrische gegevens te verzamelen buiten wat de OpenTelemetry Instrumentation-bibliotheken automatisch verzamelen. Zie Metrische gegevens in Application Insights voor meer informatie over het gebruik van metrische gegevens.
De OpenTelemetry-API biedt zes metrische 'instrumenten' voor verschillende metrische scenario's en u moet het juiste aggregatietype kiezen bij het visualiseren van metrische gegevens in Metrics Explorer. Deze vereiste geldt wanneer u de Metrische API voor OpenTelemetry gebruikt om metrische gegevens te verzenden en wanneer u een instrumentatiebibliotheek gebruikt.
In de volgende tabel ziet u de aanbevolen aggregatietypen voor elk van de metrische instrumenten van OpenTelemetry.
| OpenTelemetry-instrument |
Azure Monitor-aggregatietype |
| teller |
Som |
| Asynchrone teller |
Som |
| Histogram |
Min, Max, Average, Sum en Count |
| Asynchrone meter |
Gemiddeld |
| UpDownCounter |
Som |
| Asynchrone UpDownCounter |
Som |
Let op
Andere aggregatietypen zijn in de meeste gevallen niet zinvol.
De OpenTelemetry Specification beschrijft de instrumenten en geeft voorbeelden van wanneer u deze kunt gebruiken.
Aanbeveling
Het histogram is het meest veelzijdige en meest equivalent aan de GetMetric Classic API van Application Insights. Azure Monitor maakt het histogram-instrument momenteel plat in onze vijf ondersteunde aggregatietypen en ondersteuning voor percentielen wordt momenteel uitgevoerd. Hoewel minder veelzijdig, hebben andere OpenTelemetry-instrumenten een minder effect op de prestaties van uw toepassing.
Voorbeeld van histogram
Het opstarten van de toepassing moet zich abonneren op een meter op naam:
// 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();
De Meter moet worden geïnitialiseerd met dezelfde naam:
// 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);
}
}
Injecteren OpenTelemetry:
Een histogram maken:
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);
Notitie
De Quarkus-community ondersteunt en onderhoudt Quarkus-extensies. Gebruik Quarkus community ondersteuningskanalen voor hulp. Microsoft biedt geen technische ondersteuning voor deze integratie.
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()
Voorbeeld van teller
Het opstarten van de toepassing moet zich abonneren op een meter op naam:
// 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();
De Meter moet worden geïnitialiseerd met dezelfde naam:
// 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"));
}
}
Injecteren OpenTelemetry:
Maak de teller:
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"));
Notitie
De Quarkus-community ondersteunt en onderhoudt Quarkus-extensies. Gebruik Quarkus community ondersteuningskanalen voor hulp. Microsoft biedt geen technische ondersteuning voor deze integratie.
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()
Metervoorbeeld
Het opstarten van de toepassing moet zich abonneren op een meter op naam:
// 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();
De Meter moet worden geïnitialiseerd met dezelfde naam:
// 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"));
});
}
}
Injecteren OpenTelemetry:
Een meter maken:
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"));
});
Notitie
De Quarkus-community ondersteunt en onderhoudt Quarkus-extensies. Gebruik Quarkus community ondersteuningskanalen voor hulp. Microsoft biedt geen technische ondersteuning voor deze integratie.
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()
Aangepaste uitzonderingen toevoegen
Selecteer instrumentatiebibliotheken rapporteren automatisch uitzonderingen op Application Insights.
Het is echter mogelijk dat u uitzonderingen handmatig wilt rapporteren dan wat instrumentatiebibliotheken rapporteren.
Uitzonderingen die door uw code worden gevangen, worden bijvoorbeeld niet normaal gerapporteerd. U kunt ze rapporteren om de aandacht te vestigen op relevante ervaringen, waaronder de sectie fouten en end-to-end transactieweergaven.
Een uitzondering registreren met behulp van een activiteit:
// 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);
}
}
Een uitzondering registreren met behulp van 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" });
}
Een uitzondering registreren met behulp van een activiteit:
// 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);
}
}
Een uitzondering registreren met behulp van 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" });
}
U kunt opentelemetry-api de status van een span- en record-uitzonderingen bijwerken.
Voeg opentelemetry-api-1.0.0.jar (of hoger) toe aan uw toepassing:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Stel de status in en error noteer een uitzondering in uw code:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
Stel de status in en error noteer een uitzondering in uw code:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
De Node.js SDK exporteert handmatig vastgelegde span-gebaseerde uitzonderingen naar Application Insights als uitzonderingen alleen wanneer ze zijn vastgelegd op een bovenliggende span of een kind van een externe of interne span.
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");
}
}
De OpenTelemetry Python SDK wordt zodanig geïmplementeerd dat uitzonderingen die worden gegenereerd, automatisch worden vastgelegd en vastgelegd. Zie het volgende codevoorbeeld voor een voorbeeld van dit gedrag:
# 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")
Als u uitzonderingen handmatig wilt opnemen, kunt u deze optie in contextbeheer uitschakelen en rechtstreeks gebruiken record_exception() , zoals wordt weergegeven in het volgende voorbeeld:
...
# 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)
...
Aangepaste spanten toevoegen
U kunt een aangepaste periode toevoegen in twee scenario's. Als er eerst een afhankelijkheidsaanvraag is die nog niet is verzameld door een instrumentatiebibliotheek. Ten tweede, wanneer u een toepassingsproces wilt modelleren als een periode in de end-to-end transactieweergave.
Notitie
De Activity en ActivitySource klassen van de System.Diagnostics naamruimte vertegenwoordigen de OpenTelemetry-concepten van Span respectievelijk Tracer. U maakt ActivitySource rechtstreeks met behulp van de constructor in plaats van met behulp TracerProvidervan . Elke ActivitySource klasse moet expliciet zijn verbonden met TracerProvider behulp van AddSource(). Dit komt doordat delen van de OpenTelemetry tracing-API rechtstreeks zijn opgenomen in de .NET-runtime. Zie Inleiding tot OpenTelemetry .NET Tracing-API voor meer informatie.
// 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 is standaard ingesteld ActivityKind.Internalop , maar u kunt ook andere ActivityKind.
ActivityKind.Client, ActivityKind.Produceren ActivityKind.Internal zijn toegewezen aan Application Insights dependencies.
ActivityKind.Server en ActivityKind.Consumer zijn toegewezen aan Application Insights requests.
Notitie
De Activity en ActivitySource klassen van de System.Diagnostics naamruimte vertegenwoordigen de OpenTelemetry-concepten van Span respectievelijk Tracer. U maakt ActivitySource rechtstreeks met behulp van de constructor in plaats van met behulp TracerProvidervan . Elke ActivitySource klasse moet expliciet zijn verbonden met TracerProvider behulp van AddSource(). Dit komt doordat delen van de OpenTelemetry tracing-API rechtstreeks zijn opgenomen in de .NET-runtime. Zie Inleiding tot OpenTelemetry .NET Tracing-API voor meer informatie.
// 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 is standaard ingesteld ActivityKind.Internalop , maar u kunt ook andere ActivityKind.
ActivityKind.Client, ActivityKind.Produceren ActivityKind.Internal zijn toegewezen aan Application Insights dependencies.
ActivityKind.Server en ActivityKind.Consumer zijn toegewezen aan Application Insights requests.
De aantekening van OpenTelemetry gebruiken
De eenvoudigste manier om uw eigen spanten toe te voegen is door de aantekening van @WithSpan OpenTelemetry te gebruiken.
De reeksen vullen de requests tabellen dependencies in Application Insights.
Voeg opentelemetry-instrumentation-annotations-1.32.0.jar (of hoger) toe aan uw toepassing:
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-annotations</artifactId>
<version>1.32.0</version>
</dependency>
Gebruik de @WithSpan aantekening om een periode te verzenden telkens wanneer uw methode wordt uitgevoerd:
import io.opentelemetry.instrumentation.annotations.WithSpan;
@WithSpan(value = "your span name")
public void yourMethod() {
}
Standaard eindigt de periode in de dependencies tabel met het afhankelijkheidstype InProc.
Voor methoden die een achtergrondtaak vertegenwoordigen die niet door auto-instrumentatie worden vastgelegd, raden we u aan het kenmerk kind = SpanKind.SERVER toe te passen op de @WithSpan aantekening om ervoor te zorgen dat deze worden weergegeven in de Application Insights-tabel requests .
De OpenTelemetry-API gebruiken
Als de voorgaande Aantekening van OpenTelemetry @WithSpan niet aan uw behoeften voldoet, kunt u uw spans toevoegen met behulp van de OpenTelemetry-API.
Voeg opentelemetry-api-1.0.0.jar (of hoger) toe aan uw toepassing:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Gebruik de GlobalOpenTelemetry klasse om een Tracer:
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = GlobalOpenTelemetry.getTracer("com.example");
Maak een spanwijdte, maak deze actueel en beëindig deze:
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();
}
Injecteren OpenTelemetry:
Maak een Tracer:
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = openTelemetry.getTracer("com.example");
Maak een spanwijdte, maak deze actueel en beëindig deze:
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();
}
Notitie
De Quarkus-community ondersteunt en onderhoudt Quarkus-extensies. Gebruik Quarkus community ondersteuningskanalen voor hulp. Microsoft biedt geen technische ondersteuning voor deze integratie.
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");
}
}
De OpenTelemetry-API kan worden gebruikt om uw eigen spanten toe te voegen, die worden weergegeven in de requests en dependencies tabellen in Application Insights.
In het codevoorbeeld ziet u hoe u de tracer.start_as_current_span() methode gebruikt om te beginnen, de spanstroom te maken en de spanwijdte binnen de context te beëindigen.
...
# 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)
...
De periode bevindt zich standaard in de dependencies tabel met een afhankelijkheidstype InProc.
Als uw methode een achtergrondtaak vertegenwoordigt die nog niet is vastgelegd door auto-instrumentatie, raden we u aan het kenmerk kind = SpanKind.SERVER in te stellen om ervoor te zorgen dat deze wordt weergegeven in de Application Insights-tabel requests .
...
# 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.
...
Aangepaste gebeurtenissen verzenden
Application Insights slaat aangepaste gebeurtenissen op in de customEvents tabel. Een manier om ze te analyseren, filteren en visualiseren , is door gebruik te maken van de Application Insights-gebruikservaringen.
Als u de verzameling interactiegebeurtenissen aan de clientzijde wilt automatiseren, kunt u de invoegtoepassing gebruiken in de JavaScript SDK.
Aangepaste gebeurtenissen bevinden zich in openbare preview en gebruiken Azure.Monitor.OpenTelemetry.AspNetCore 1.3.0-beta.3.
Om een CustomEvent te verzenden met behulp van ILogger, stelt u het "microsoft.custom_event.name" kenmerk in de berichtsjabloon in.
// 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");
Aangepaste gebeurtenissen bevinden zich in openbare preview en gebruiken Azure.Monitor.OpenTelemetry.Exporter 1.4.0-beta.3.
Om een CustomEvent te verzenden met behulp van ILogger, stelt u het "microsoft.custom_event.name" kenmerk in de berichtsjabloon in.
// 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");
Als u een customEvent met de Java-agent wilt verzenden, stelt u het "microsoft.custom_event.name" kenmerk in op de OpenTelemetry-logboekrecord.
Afhankelijk van of de Java-agent van Application Insights wordt gebruikt of de automatische configuratie-SDK, is de manier om de OpenTelemetry-logboekregistratie op te halen iets anders. Dit detail wordt verder uitgelegd in de volgende voorbeelden.
Voor de Java-agent voor 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();
Voor automatische configuratie-SDK:
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();
Als u aangepaste gebeurtenissen betrouwbaar wilt verzenden, gebruikt u de OpenTelemetry-API rechtstreeks. Sommige logboekframeworks bieden geen ondersteuning voor het toevoegen of parseren van het kenmerk aangepaste gebeurtenissen.
Het is niet mogelijk om een customEvent kenmerk te verzenden met behulp van het "microsoft.custom_event.name" kenmerk in systeemeigen Java.
Als u een customEvent wilt verzenden met behulp van logger.emit, stelt u het kenmerk "microsoft.custom_event.name" in het attributes-object van het logboek in. Andere kenmerken kunnen ook indien nodig worden opgenomen.
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");
}
}
Als u een customEvent in Python wilt verzenden, gebruikt u de logboekregistratiebibliotheek met het "microsoft.custom_event.name" kenmerk in de extra parameter.
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"
}
)
Telemetrie wijzigen
In deze sectie wordt uitgelegd hoe u telemetrie kunt wijzigen.
Spankenmerken toevoegen
Deze kenmerken kunnen bestaan uit het toevoegen van een aangepaste eigenschap aan uw telemetrie. U kunt ook kenmerken gebruiken om optionele velden in te stellen in het Application Insights-schema, zoals client-IP.
Een aangepaste eigenschap toevoegen aan een span
Alle kenmerken die u aan spans toevoegt, worden geëxporteerd als aangepaste eigenschappen. Ze vullen het veld customDimensions in de tabel met aanvragen, afhankelijkheden, traceringen of uitzonderingen.
Als u spankenmerken wilt toevoegen, gebruikt u een van de volgende twee manieren:
Aanbeveling
Het voordeel van het gebruik van opties die worden geboden door instrumentatiebibliotheken, wanneer deze beschikbaar zijn, is dat de volledige context beschikbaar is. Hierdoor kunnen gebruikers ervoor kiezen om meer kenmerken toe te voegen of te filteren. De verrijkingsoptie in de HttpClient-instrumentatiebibliotheek geeft gebruikers bijvoorbeeld toegang tot httpRequestMessage en httpResponseMessagezelf. Ze kunnen er alles uit selecteren en opslaan als een kenmerk.
Veel instrumentatiebibliotheken bieden een verrijkingsoptie. Zie de leesmij-bestanden van afzonderlijke instrumentatiebibliotheken voor hulp:
Een aangepaste processor gebruiken:
Aanbeveling
Voeg de hier weergegeven processor toe voordat u Azure Monitor toevoegt.
// 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();
Voeg ActivityEnrichingProcessor.cs toe aan uw project met de volgende code:
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");
}
}
Als u spankenmerken wilt toevoegen, gebruikt u een van de volgende twee manieren:
- Gebruik opties die worden geboden door instrumentatiebibliotheken.
- Voeg een aangepaste spanprocessor toe.
Aanbeveling
Het voordeel van het gebruik van opties die worden geboden door instrumentatiebibliotheken, wanneer deze beschikbaar zijn, is dat de volledige context beschikbaar is. Hierdoor kunnen gebruikers ervoor kiezen om meer kenmerken toe te voegen of te filteren. De verrijkingsoptie in de HttpClient-instrumentatiebibliotheek geeft gebruikers bijvoorbeeld toegang tot de httpRequestMessage zelf. Ze kunnen er alles uit selecteren en opslaan als een kenmerk.
Veel instrumentatiebibliotheken bieden een verrijkingsoptie. Zie de leesmij-bestanden van afzonderlijke instrumentatiebibliotheken voor hulp:
Een aangepaste processor gebruiken:
Aanbeveling
Voeg de hier weergegeven processor toe vóór de Azure Monitor-exporteur.
// 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();
Voeg ActivityEnrichingProcessor.cs toe aan uw project met de volgende code:
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");
}
}
U kunt opentelemetry-api kenmerken toevoegen om spans toe te voegen.
Als u een of meer spankenmerken toevoegt, wordt het customDimensions veld in de requests, dependenciesof tracesexceptionstabel ingevuld.
Voeg opentelemetry-api-1.0.0.jar (of hoger) toe aan uw toepassing:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Aangepaste dimensies toevoegen aan uw code:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
Aangepaste dimensies toevoegen aan uw code:
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");
}
}
Een aangepaste processor gebruiken:
...
# 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],
)
...
Voeg SpanEnrichingProcessor toe aan uw project met de volgende code:
# 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"
Het IP-adres van de gebruiker instellen
U kunt het client_IP veld voor aanvragen vullen door een kenmerk in te stellen op het bereik. Application Insights gebruikt het IP-adres om kenmerken van gebruikerslocatie te genereren en verwijdert het vervolgens standaard.
Gebruik het voorbeeld van de aangepaste eigenschap, maar vervang de volgende coderegels 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>");
Gebruik het voorbeeld van de aangepaste eigenschap, maar vervang de volgende coderegels 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>");
Dit veld wordt automatisch ingevuld in Java.
Dit veld wordt automatisch ingevuld.
Gebruik het voorbeeld van de aangepaste eigenschap, maar vervang de volgende regels code:
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.");
}
}
Gebruik het voorbeeld van de aangepaste eigenschap, maar vervang de volgende coderegels in SpanEnrichingProcessor.py:
# Set the `http.client_ip` attribute of the span to the specified IP address.
span._attributes["http.client_ip"] = "<IP Address>"
De gebruikers-id of geverifieerde gebruikers-id instellen
U kunt het veld user_Id of user_AuthenticatedId voor aanvragen vullen met behulp van de volgende richtlijnen. Gebruikers-id is een anonieme gebruikers-id. Geverifieerde gebruikers-id is een bekende gebruikers-id.
Belangrijk
Raadpleeg de toepasselijke privacywetgeving voordat u de geverifieerde gebruikers-id instelt.
Vul het user ID veld in de requeststabel of dependenciesexceptions de tabel in.
Voeg opentelemetry-api-1.0.0.jar (of hoger) toe aan uw toepassing:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Instellen user_Id in uw code:
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser"); // (user_AuthenticatedId)
Span.current().setAttribute("enduser.pseudo.id", "myuser"); // (user_Id)
Vul het user ID veld in de requeststabel of dependenciesexceptions de tabel in.
Instellen user_Id in uw code:
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser"); // (user_AuthenticatedId)
Span.current().setAttribute("enduser.pseudo.id", "myuser"); // (user_Id)
Gebruik het voorbeeld van de aangepaste eigenschap, maar vervang de volgende regels code:
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.");
}
}
Gebruik het voorbeeld van de aangepaste eigenschap, maar vervang de volgende regels code:
# Set the `enduser.id` attribute of the span to the specified user ID.
span._attributes["enduser.id"] = "<User ID>"
Logboekkenmerken toevoegen
OpenTelemetry maakt gebruik van . NET's ILogger.
Het koppelen van aangepaste dimensies aan logboeken kan worden uitgevoerd met behulp van een berichtsjabloon.
OpenTelemetry maakt gebruik van . NET's ILogger.
Het koppelen van aangepaste dimensies aan logboeken kan worden uitgevoerd met behulp van een berichtsjabloon.
Logback, Log4j en java.util.logging worden automatisch geïnstrueerd. Als u aangepaste dimensies aan uw logboeken koppelt, kunt u dit op deze manieren doen:
Voor systeemeigen Spring Boot-toepassingen wordt Logback out-of-the-box geïnstrueerd.
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");
}
}
De Python logboekbibliotheek is geautomatiseerd geïnstrumenteerd. U kunt aangepaste dimensies toevoegen aan uw logboeken door een woordenlijst door te geven aan het extra argument van uw logboeken:
...
# Create a warning log message with the properties "key1" and "value1".
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
De tracerings-id of span-id ophalen
U kunt de Trace ID en Span ID van de momenteel actieve Span verkrijgen met behulp van de volgende stappen.
Notitie
De Activity en ActivitySource klassen van de System.Diagnostics naamruimte vertegenwoordigen de OpenTelemetry-concepten van Span respectievelijk Tracer. Dit komt doordat delen van de OpenTelemetry tracing-API rechtstreeks zijn opgenomen in de .NET-runtime. Zie Inleiding tot OpenTelemetry .NET Tracing-API voor meer informatie.
// 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();
Notitie
De Activity en ActivitySource klassen van de System.Diagnostics naamruimte vertegenwoordigen de OpenTelemetry-concepten van Span respectievelijk Tracer. Dit komt doordat delen van de OpenTelemetry tracing-API rechtstreeks zijn opgenomen in de .NET-runtime. Zie Inleiding tot OpenTelemetry .NET Tracing-API voor meer informatie.
// 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();
U kunt de opentelemetry-api tracerings-id of span-id ophalen.
Voeg opentelemetry-api-1.0.0.jar (of hoger) toe aan uw toepassing:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Haal de aanvraagtracerings-id en de span-id in uw code op:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
Haal de aanvraagtracerings-id en de span-id in uw code op:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
Haal de aanvraagtracerings-id en de span-id in uw code op:
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);
}
}
Haal de aanvraagtracerings-id en de span-id in uw code op:
# 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
Volgende stappen
Notitie
De Quarkus-community ondersteunt en onderhoudt Quarkus-extensies. Gebruik Quarkus community ondersteuningskanalen voor hulp. Microsoft biedt geen technische ondersteuning voor deze integratie.
- Als u de broncode en extra documentatie wilt bekijken, raadpleegt u de GitHub-opslagplaats van Azure Monitor Distro.
- Zie Voorbeelden van Azure Monitor Distro voor extra voorbeelden en use cases.
- Als u de releaseopmerkingen wilt bekijken, raadpleegt u de opmerkingen bij de release op GitHub.
- Als u het PyPI-pakket wilt installeren, controleert u op updates of bekijkt u de releaseopmerkingen van Azure Monitor Distro PyPI Package .
- Als u meer vertrouwd wilt raken met Azure Monitor Application Insights en OpenTelemetry, raadpleegt u de Azure Monitor-voorbeeldtoepassing.
- Zie de OpenTelemetry Python GitHub-opslagplaats voor meer informatie over OpenTelemetry en de bijbehorende community.
- Als u beschikbare OpenTelemetry-instrumentaties en -onderdelen wilt zien, raadpleegt u de OpenTelemetry Contributor Python GitHub-repository.
- Als u gebruikservaringen wilt inschakelen, schakelt u bewaking van web- of browsergebruikers in.
- Als u veelgestelde vragen, probleemoplossingsstappen, ondersteuningsopties of OpenTelemetry-feedback wilt geven, raadpleegt u De Help, ondersteuning en feedback van OpenTelemetry voor Azure Monitor Application Insights.