Den här guiden innehåller instruktioner för att integrera och anpassa OpenTelemetry-instrumentation (OTel) inom Azure Monitor Application Insights.
Använd Microsoft OpenTelemetry Distro för .NET, Node.jsoch Python. Java fortsätter att använda Azure Monitor OpenTelemetry Distro och dess agent- eller native-image-integreringar. Först, aktivera OpenTelemetry för ditt språk. Ersätt den grundläggande initieringen med det relevanta exemplet. Initiera inte en andra distro eller provider för samma signal.
Microsoft OpenTelemetry Distro-paketidentifierare och installationskommandon är:
| Språk |
Package |
Installationskommando |
| Python |
microsoft-opentelemetry |
pip install microsoft-opentelemetry |
| Node.js |
@microsoft/opentelemetry |
npm install @microsoft/opentelemetry |
| .NET |
Microsoft.OpenTelemetry |
dotnet add package Microsoft.OpenTelemetry |
Ange APPLICATIONINSIGHTS_CONNECTION_STRING innan du startar exempel som inte anger det i kod. Håll leverantörerna vid liv under programmets livslängd och skicka telemetridata vid avstängning. Initiera Node.js-instrumentering innan programbibliotek läses in. ESM-program måste förinläsa Microsoft OpenTelemetry Distro-inläsaren.
Mer information om OpenTelemetry-begrepp finns i Översikt över OpenTelemetry.
För de bibliotek som ingår i varje distro, se Automatisk datainsamling och resursdetektorer.
Du kan samla in mer data automatiskt när du inkluderar instrumentationsbibliotek från OpenTelemetry-communityn.
Varning
Vi stöder inte eller garanterar inte kvaliteten på community-instrumentationsbibliotek. För att föreslå en för vår distribution kan du posta eller rösta upp i vår feedbackgemenskap. Tänk på att vissa baseras på experimentella OpenTelemetry-specifikationer och kan introducera ändringar som bryter kompatibilitet i framtiden.
Om du vill lägga till ett community-bibliotek använder du ConfigureOpenTelemetryMeterProvider metoderna eller ConfigureOpenTelemetryTracerProvider när du har lagt till NuGet-paketet för biblioteket.
I följande exempel visas hur du lägger till Runtime-instrumentation för att samla in extra metriker:
dotnet add package OpenTelemetry.Instrumentation.Runtime
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry.Metrics;
// 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());
// Configure the Microsoft OpenTelemetry Distro.
// Export collected telemetry to Azure Monitor.
builder.Services.AddOpenTelemetry().UseMicrosoftOpenTelemetry(options =>
options.Exporters = ExportTarget.AzureMonitor);
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Om du vill samla in valfria körningsmått i en konsol eller något annat icke-värdbaserat program, installerar du OpenTelemetry.Instrumentation.Runtime och utökar din befintliga konfiguration av mätarprovidern som visas. Det här steget krävs inte för grundläggande distrokonfiguration. Initiera inte ytterligare en SDK-instans:
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry;
using OpenTelemetry.Metrics;
// Create the SDK and keep its providers alive until application shutdown.
using var sdk = OpenTelemetrySdk.Create(telemetry =>
{
// Configure the Microsoft OpenTelemetry Distro.
telemetry.UseMicrosoftOpenTelemetry(options =>
options.Exporters = ExportTarget.AzureMonitor)
// Collect runtime metrics through the distro meter provider.
.WithMetrics(metrics => metrics.AddRuntimeInstrumentation());
});
Du kan inte utöka Java-agenter med community-instrumentationsbibliotek. Om du vill begära att andra instrumentationsbibliotek ska inkluderas öppnar du ett problem på sidan GitHub.
Du kan inte använda community-bibliotek för instrumentation med GraalVM Java inhemska applikationer.
export class RegisterExpressInstrumentationSample {
static async run() {
// Import the Microsoft OpenTelemetry Distro and Express instrumentation
const { useMicrosoftOpenTelemetry } = await import("@microsoft/opentelemetry");
const { registerInstrumentations } = await import(
"@opentelemetry/instrumentation"
);
const { ExpressInstrumentation } = await import(
"@opentelemetry/instrumentation-express"
);
// Initialize the Microsoft OpenTelemetry Distro using the environment settings
useMicrosoftOpenTelemetry({
azureMonitor: {},
});
// Register the Express instrumentation
registerInstrumentations({
instrumentations: [new ExpressInstrumentation()],
});
console.log("Express instrumentation registered");
}
}
Om du vill lägga till ett bibliotek av community-instrumentation kan du instrumentera direkt med instrumenteringarna. Du kan hitta listan över bibliotek för gemenskapsinstrumentation på GitHub.
Kommentar
Instrumentera inte manuellt ett instrumentationsbibliotek som stöds som use_microsoft_opentelemetry() redan instrumenterar. Duplicerad instrumentering stöds inte och kan påverka din telemetri.
# Import the `use_microsoft_opentelemetry()`, `SQLAlchemyInstrumentor`, `create_engine`,
# and `text` functions from the appropriate packages.
from microsoft.opentelemetry import use_microsoft_opentelemetry
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
from sqlalchemy import create_engine, text
# Configure OpenTelemetry to use Azure Monitor.
use_microsoft_opentelemetry(
enable_azure_monitor=True,
)
# 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
# `use_microsoft_opentelemetry()`.
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())
Samla in anpassad telemetri
I det här avsnittet beskrivs hur du samlar in anpassad telemetri från ditt program.
Beroende på språk och signaltyp finns det olika sätt att samla in anpassad telemetri, inklusive:
- OpenTelemetry-API
- Språkspecifika loggnings-/måttbibliotek
Följande tabell representerar de anpassade telemetrityper som stöds för närvarande:
| Språk |
Anpassade händelser |
Anpassade mått |
Beroenden |
Undantag |
Sidvisningar |
begäranden |
Spårningar |
|
ASP.NET Core |
|
|
|
|
|
|
|
| OpenTelemetry-API |
|
Ja |
Ja |
Ja |
|
Ja |
|
ILogger API (applikationsprogrammeringsgränssnitt) |
Ja |
|
|
|
|
|
Ja |
|
|
|
|
|
|
|
|
|
Java |
|
|
|
|
|
|
|
| OpenTelemetry-API |
Ja |
Ja |
Ja |
Ja |
|
Ja |
|
Logback, Log4j, JUL |
|
|
|
Ja |
|
|
Ja |
| Mått för Micrometer |
|
Ja |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Node.js |
|
|
|
|
|
|
|
| OpenTelemetry-API |
Ja |
Ja |
Ja |
Ja |
|
Ja |
|
|
|
|
|
|
|
|
|
|
Python |
|
|
|
|
|
|
|
| OpenTelemetry-API |
|
Ja |
Ja |
Ja |
|
Ja |
|
| Python loggningsmodul |
|
|
|
|
|
|
Ja |
| Händelsetillägg |
Ja |
|
|
|
|
|
Ja |
Lägga till anpassade mått
I det här sammanhanget refererar den anpassade måtttermen till att manuellt instrumentera koden för att samla in extra mått utöver vad OpenTelemetry Instrumentation Libraries automatiskt samlar in. Mer information om hur du använder mått finns i Mått i Application Insights.
OpenTelemetry-API:et erbjuder sex måttinstrument för olika måttscenarier och du måste välja rätt sammansättningstyp när du visualiserar mått i Metrics Explorer. Det här kravet gäller när du använder OPENTelemetry Metric API för att skicka mått och när du använder ett instrumentationsbibliotek.
I följande tabell visas de rekommenderade aggregeringstyperna för vart och ett av Måttinstrumenten för OpenTelemetry.
| OpenTelemetry-instrument |
Azure Monitor aggregationstyp |
| Räknare |
Summa |
| Asynkron räknare |
Summa |
| Histogram |
Min, Max, Genomsnitt, Summa och Antal |
| Asynkron mätare |
Genomsnitt |
| Upp-och-ner-räknare |
Summa |
| Asynkron Räknare upp och ner |
Summa |
Varning
Andra sammansättningstyper är i de flesta fall inte meningsfulla.
OpenTelemetry Specification beskriver instrumenten och innehåller exempel på när du kan använda var och en.
Tips
Histogrammet är det mest mångsidiga OpenTelemetrys måttinstrument för att registrera distributioner. Azure Monitor utjämnar för närvarande histograminstrumentet till de fem aggregationstyper som stöds och stöd för percentiler är under utveckling. Även om de är mindre mångsidiga har andra OpenTelemetry-instrument en mindre effekt på programmets prestanda.
Histogramexempel
Applikationsstart måste prenumerera på en mätare med namnet:
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry.Metrics;
// 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"));
// Configure the Microsoft OpenTelemetry Distro.
// Export collected telemetry to Azure Monitor.
builder.Services.AddOpenTelemetry().UseMicrosoftOpenTelemetry(options =>
options.Exporters = ExportTarget.AzureMonitor);
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Meter Måste initieras med samma namn:
using System.Diagnostics.Metrics;
// 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"));
Registrera histogrammått
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using System.Diagnostics.Metrics;
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 sdk = OpenTelemetrySdk.Create(telemetry =>
{
// Configure the Microsoft OpenTelemetry Distro.
telemetry.UseMicrosoftOpenTelemetry(options =>
options.Exporters = ExportTarget.AzureMonitor)
// Collect measurements from the application meter.
.WithMetrics(metrics => metrics.AddMeter("OTel.AzureMonitor.Demo"));
});
// 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);
}
}
För in OpenTelemetry
Vår
import io.opentelemetry.api.OpenTelemetry;
import org.springframework.beans.factory.annotation.Autowired;
@Autowired
OpenTelemetry openTelemetry;
Kvarkarus
import io.opentelemetry.api.OpenTelemetry;
import jakarta.inject.Inject;
@Inject
OpenTelemetry openTelemetry;
Skapa ett histogram:
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);
Kommentar
Quarkus-communityn stöder och underhåller Quarkus-tillägg. Om du vill ha hjälp använder du Quarkus community-supportkanaler. Microsoft tillhandahåller inte teknisk support för den här integreringen.
export class HistogramSample {
static async run() {
// Import the Microsoft OpenTelemetry Distro and metrics API
const { useMicrosoftOpenTelemetry } = await import("@microsoft/opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize the Microsoft OpenTelemetry Distro
useMicrosoftOpenTelemetry({
azureMonitor: {
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING ||
"<ConnectionString>",
},
},
});
// 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");
}
}
Registrera histogrammått
# Import the `use_microsoft_opentelemetry()` and `metrics` functions from the appropriate
# packages.
from microsoft.opentelemetry import use_microsoft_opentelemetry
from opentelemetry import metrics
import os
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
use_microsoft_opentelemetry(
enable_azure_monitor=True,
azure_monitor_connection_string="<ConnectionString>",
)
# 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()
Motexempel
Applikationsstart måste prenumerera på en mätare med namnet:
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry.Metrics;
// 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"));
// Configure the Microsoft OpenTelemetry Distro.
// Export collected telemetry to Azure Monitor.
builder.Services.AddOpenTelemetry().UseMicrosoftOpenTelemetry(options =>
options.Exporters = ExportTarget.AzureMonitor);
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Meter Måste initieras med samma namn:
using System.Diagnostics.Metrics;
// 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"));
Mätvärden för räknare
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using System.Diagnostics.Metrics;
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 sdk = OpenTelemetrySdk.Create(telemetry =>
{
// Configure the Microsoft OpenTelemetry Distro.
telemetry.UseMicrosoftOpenTelemetry(options =>
options.Exporters = ExportTarget.AzureMonitor)
// Collect measurements from the application meter.
.WithMetrics(metrics => metrics.AddMeter("OTel.AzureMonitor.Demo"));
});
// 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();
}
}
Mätvärden för posträknare
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"));
}
}
För in OpenTelemetry
Vår
import io.opentelemetry.api.OpenTelemetry;
import org.springframework.beans.factory.annotation.Autowired;
@Autowired
OpenTelemetry openTelemetry;
Kvarkarus
import io.opentelemetry.api.OpenTelemetry;
import jakarta.inject.Inject;
@Inject
OpenTelemetry openTelemetry;
Skapa räknaren:
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"));
Kommentar
Quarkus-communityn stöder och underhåller Quarkus-tillägg. Om du vill ha hjälp använder du Quarkus community-supportkanaler. Microsoft tillhandahåller inte teknisk support för den här integreringen.
Mätvärden för posträknare
export class CounterSample {
static async run() {
// Import the Microsoft OpenTelemetry Distro and metrics API
const { useMicrosoftOpenTelemetry } = await import("@microsoft/opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize the Microsoft OpenTelemetry Distro
useMicrosoftOpenTelemetry({
azureMonitor: {
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING ||
"<ConnectionString>",
},
},
});
// 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");
}
}
Mätvärden för posträknare
# Import the `use_microsoft_opentelemetry()` and `metrics` functions from the appropriate
# packages.
from microsoft.opentelemetry import use_microsoft_opentelemetry
from opentelemetry import metrics
import os
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
use_microsoft_opentelemetry(
enable_azure_monitor=True,
azure_monitor_connection_string="<ConnectionString>",
)
# 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()
Mätarexempel
Applikationsstart måste prenumerera på en mätare med namnet:
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry.Metrics;
// 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"));
// Configure the Microsoft OpenTelemetry Distro.
// Export collected telemetry to Azure Monitor.
builder.Services.AddOpenTelemetry().UseMicrosoftOpenTelemetry(options =>
options.Exporters = ExportTarget.AzureMonitor);
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Meter Måste initieras med samma namn:
using System.Diagnostics;
using System.Diagnostics.Metrics;
// 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));
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));
}
}
Registrera observerbara gauge-mätvärden
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using System.Diagnostics.Metrics;
using System.Diagnostics;
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 sdk = OpenTelemetrySdk.Create(telemetry =>
{
// Configure the Microsoft OpenTelemetry Distro.
telemetry.UseMicrosoftOpenTelemetry(options =>
options.Exporters = ExportTarget.AzureMonitor)
// Collect measurements from the application meter.
.WithMetrics(metrics => metrics.AddMeter("OTel.AzureMonitor.Demo"));
});
// 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"));
});
}
}
För in OpenTelemetry
Vår
import io.opentelemetry.api.OpenTelemetry;
import org.springframework.beans.factory.annotation.Autowired;
@Autowired
OpenTelemetry openTelemetry;
Kvarkarus
import io.opentelemetry.api.OpenTelemetry;
import jakarta.inject.Inject;
@Inject
OpenTelemetry openTelemetry;
Skapa en mätare:
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"));
});
Kommentar
Quarkus-communityn stöder och underhåller Quarkus-tillägg. Om du vill ha hjälp använder du Quarkus community-supportkanaler. Microsoft tillhandahåller inte teknisk support för den här integreringen.
export class GaugeSample {
static async run() {
// Import the Microsoft OpenTelemetry Distro and metrics API
const { useMicrosoftOpenTelemetry } = await import("@microsoft/opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize the Microsoft OpenTelemetry Distro
useMicrosoftOpenTelemetry({
azureMonitor: {
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING ||
"<ConnectionString>",
},
},
});
// 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");
}
}
Registrera observerbara gauge-metrik
# Import the necessary packages.
from typing import Iterable
import os
from microsoft.opentelemetry import use_microsoft_opentelemetry
from opentelemetry import metrics
from opentelemetry.metrics import CallbackOptions, Observation
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
use_microsoft_opentelemetry(
enable_azure_monitor=True,
azure_monitor_connection_string="<ConnectionString>",
)
# 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()
Lägga till anpassade undantag
Välj instrumentationsbibliotek rapporterar automatiskt undantag till Application Insights.
Du kanske dock vill rapportera undantag manuellt, utöver de som instrumenteringsbibliotek rapporterar.
Till exempel rapporteras undantag som fångas av din kod vanligtvis inte. Du kanske vill rapportera dem för att uppmärksamma relevanta upplevelser, inklusive avsnittet fel och heltäckande transaktionsvyer.
De .NET exemplen är fragment för ett redan instrumenterat program. För aktivitetsexempel använder du det registrerade activitySource från Lägg till anpassade spann.
I loggningsexemplen använder du programmets konfigurerade ILoggerFactory som loggerFactory.
Så här loggar du ett undantag med hjälp av en aktivitet:
using System.Diagnostics;
using OpenTelemetry.Trace;
// 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);
}
}
Så här loggar du ett undantag med :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 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" });
}
Så här loggar du ett undantag med hjälp av en aktivitet:
using System.Diagnostics;
using OpenTelemetry.Trace;
// 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);
}
}
Så här loggar du ett undantag med :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" });
}
Du kan använda opentelemetry-api för att uppdatera statusen för ett spann och registrera undantag.
Lägg till opentelemetry-api-1.0.0.jar (eller senare) i ditt program:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Ange status till error och registrera ett undantag i koden:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
Ange status till error och registrera ett undantag i koden:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
Node.js SDK exporterar manuellt registrerade span-baserade undantag till Application Insights som undantag endast när de registreras på ett toppnivåspann eller som ett underordnat spann till ett fjärr- eller internt spann.
Registrera anpassade undantag
export class CustomExceptionSample {
static async run() {
// Import the Microsoft OpenTelemetry Distro and tracing API
const { useMicrosoftOpenTelemetry } = await import("@microsoft/opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize the Microsoft OpenTelemetry Distro
useMicrosoftOpenTelemetry({
azureMonitor: {
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING ||
"<ConnectionString>",
},
},
});
// 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");
}
}
OpenTelemetry Python SDK implementeras på ett sådant sätt att undantag som kastas automatiskt fångas upp och registreras. Se följande kodexempel för ett exempel på det här beteendet:
# Import the necessary packages.
from microsoft.opentelemetry import use_microsoft_opentelemetry
from opentelemetry import trace
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
use_microsoft_opentelemetry(
enable_azure_monitor=True,
azure_monitor_connection_string="<ConnectionString>",
)
# 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")
Om du vill registrera undantag manuellt kan du inaktivera det alternativet i kontexthanteraren och använda record_exception() direkt enligt följande exempel:
...
# 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)
...
Lägga till anpassade intervall
Du kanske vill lägga till ett anpassat spann i två scenarier. Först när en beroendeförfrågan inte redan har samlats in av ett instrumentationsbibliotek. För det andra, när du vill modellera en programmeringsprocess som en sträcka i transaktionsvyn från början till slut.
Kommentar
Klasserna Activity och ActivitySource från System.Diagnostics namnområdet representerar OpenTelemetry-begreppen Span för respektive Tracer. Du skapar ActivitySource direkt med konstruktorn i stället för med hjälp av TracerProvider. Varje ActivitySource-klass måste uttryckligen anslutas till TracerProvider med hjälp av AddSource(). Det beror på att delar av OpenTelemetry-spårnings-API:et införlivas direkt i .NET-körningen. Mer information finns i Introduction to OpenTelemetry .NET Tracing API.
Lägg till anpassade spann
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using System.Diagnostics;
using OpenTelemetry.Trace;
// Define an activity source named "ActivitySourceName". This activity source will be used
// to create activities for all requests to the application.
using var activitySource = new ActivitySource("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"));
// Configure the Microsoft OpenTelemetry Distro. This service will collect
// and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseMicrosoftOpenTelemetry(options =>
options.Exporters = ExportTarget.AzureMonitor);
// 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 standardvärdet är ActivityKind.Internal, men du kan ange andra ActivityKind.
ActivityKind.Client, ActivityKind.Produceroch ActivityKind.Internal mappas till Application Insights dependencies.
ActivityKind.Server och ActivityKind.Consumer mappas till Application Insights requests.
Kommentar
Klasserna Activity och ActivitySource från System.Diagnostics namnområdet representerar OpenTelemetry-begreppen Span för respektive Tracer. Du skapar ActivitySource direkt med konstruktorn i stället för med hjälp av TracerProvider. Varje ActivitySource-klass måste uttryckligen anslutas till TracerProvider med hjälp av AddSource(). Det beror på att delar av OpenTelemetry-spårnings-API:et införlivas direkt i .NET-körningen. Mer information finns i Introduction to OpenTelemetry .NET Tracing API.
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry;
using OpenTelemetry.Trace;
using System.Diagnostics;
// Create the SDK and keep its providers alive until application shutdown.
using var sdk = OpenTelemetrySdk.Create(telemetry =>
{
// Configure the Microsoft OpenTelemetry Distro.
telemetry.UseMicrosoftOpenTelemetry(options =>
options.Exporters = ExportTarget.AzureMonitor)
.WithTracing(tracing => tracing.AddSource("ActivitySourceName"));
});
// 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 standardvärdet är ActivityKind.Internal, men du kan ange andra ActivityKind.
ActivityKind.Client, ActivityKind.Produceroch ActivityKind.Internal mappas till Application Insights dependencies.
ActivityKind.Server och ActivityKind.Consumer mappas till Application Insights requests.
Använda OpenTelemetry-kommentaren
Det enklaste sättet att lägga till egna spann är att använda OpenTelemetrys @WithSpan anteckning.
Spans befolkar tabellerna requests och dependencies i Application Insights.
Lägg till opentelemetry-instrumentation-annotations-1.32.0.jar (eller senare) i ditt program:
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-annotations</artifactId>
<version>1.32.0</version>
</dependency>
Använd kommentaren @WithSpan för att generera ett intervall varje gång metoden körs:
import io.opentelemetry.instrumentation.annotations.WithSpan;
@WithSpan(value = "your span name")
public void yourMethod() {
}
Som standard hamnar intervallet i dependencies tabellen med beroendetypen InProc.
För metoder som representerar ett bakgrundsjobb som inte fångas upp av autoinstrumentation rekommenderar vi att du tillämpar attributet kind = SpanKind.SERVER på anteckningen @WithSpan för att säkerställa att de visas i tabellen Application Insights requests .
Använda OpenTelemetry-API:et
Om föregående OpenTelemetry-anteckning @WithSpan inte uppfyller dina behov kan du lägga till dina spann med hjälp av OpenTelemetry-API:et.
Lägg till opentelemetry-api-1.0.0.jar (eller senare) i ditt program:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Använd GlobalOpenTelemetry-klassen för att skapa en Tracer.
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = GlobalOpenTelemetry.getTracer("com.example");
Skapa ett spann, gör det aktuellt och avsluta det sedan:
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();
}
För in OpenTelemetry
Vår
import io.opentelemetry.api.OpenTelemetry;
import org.springframework.beans.factory.annotation.Autowired;
@Autowired
OpenTelemetry openTelemetry;
Kvarkarus
import io.opentelemetry.api.OpenTelemetry;
import jakarta.inject.Inject;
@Inject
OpenTelemetry openTelemetry;
Skapa en Tracer i din instrumenterade metod efter att ramverket har injicerat OpenTelemetry:
import io.opentelemetry.api.trace.Tracer;
Tracer tracer = openTelemetry.getTracer("com.example");
Skapa ett spann, gör det aktuellt och avsluta det sedan:
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();
}
Kommentar
Quarkus-communityn stöder och underhåller Quarkus-tillägg. Om du vill ha hjälp använder du Quarkus community-supportkanaler. Microsoft tillhandahåller inte teknisk support för den här integreringen.
Lägga till anpassade spann
export class CustomTraceSample {
static async run() {
// Import the Microsoft OpenTelemetry Distro and tracing API
const { useMicrosoftOpenTelemetry } = await import("@microsoft/opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize the Microsoft OpenTelemetry Distro
useMicrosoftOpenTelemetry({
azureMonitor: {
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING ||
"<ConnectionString>",
},
},
});
// 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 < 1000000; i++) {
/* simulate work */
}
} catch (err) {
span.recordException(err as Error);
}
finally {
span.end();
}
console.log("Custom span recorded");
}
}
OpenTelemetry-API:et kan användas för att lägga till dina egna intervall, som visas i tabellerna requests och dependencies i Application Insights.
Kodexemplet visar hur du använder tracer.start_as_current_span() metoden för att starta, göra intervallet aktuellt och avsluta intervallet i dess kontext.
...
# 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)
...
Som standard finns intervallet i dependencies tabellen med beroendetypen InProc.
Om din metod representerar ett bakgrundsjobb som inte redan har registrerats med autoinstrumentation rekommenderar vi att du anger attributet kind = SpanKind.SERVER så att det visas i tabellen Application Insights 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.
...
...
Skicka anpassade händelser
Application Insights lagrar anpassade händelser i customEvents tabellen. Ett sätt att analysera, filtrera och visualisera dem är att använda Application Insights-användningsupplevelserna.
Om du vill automatisera samlingen av interaktionshändelser på klientsidan kan du använda plugin-programmet i JavaScript SDK.
Microsoft OpenTelemetry Distro för .NET skickar anpassade händelser via Azure Monitor-loggexportören.
För att skicka en CustomEvent med hjälp av ILogger, ange "microsoft.custom_event.name"-attributet i meddelandemallen.
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
// Create the application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the Microsoft OpenTelemetry Distro.
builder.UseMicrosoftOpenTelemetry(options =>
{
options.Exporters = ExportTarget.AzureMonitor;
});
// Build the application with the configured telemetry services.
var app = builder.Build();
// Use the message-template attribute to name the custom event.
app.Logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}",
"test-event-name", "val1");
// Run the application and its telemetry providers.
app.Run();
Microsoft OpenTelemetry Distro för .NET skickar anpassade händelser via Azure Monitor-loggexportören. I det här konsolexemplet används .NET Generic Host för att hantera loggningspipelinens och SDK:s livslängd.
För att skicka en CustomEvent med hjälp av ILogger, ange "microsoft.custom_event.name"-attributet i meddelandemallen.
Skicka anpassade händelser
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
// Create the application host builder.
var builder = Host.CreateApplicationBuilder(args);
// Configure the Microsoft OpenTelemetry Distro.
builder.UseMicrosoftOpenTelemetry(options =>
{
options.Exporters = ExportTarget.AzureMonitor;
});
// Keep the host alive until shutdown; disposal flushes pending telemetry.
using var host = builder.Build();
// Start telemetry collection before recording events.
await host.StartAsync();
// Create a logger for the custom-events category.
var logger = host.Services.GetRequiredService<ILoggerFactory>().CreateLogger(
"custom-events");
// Use the message-template attribute to name the custom event.
logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}",
"test-event-name", "val1");
await host.StopAsync();
Om du vill skicka ett customEvent med Java-agenten anger du attributet "microsoft.custom_event.name" på loggposten OpenTelemetry.
Beroende på om Application Insights-Java agenten används eller SDK:t för automatisk konfiguration är sättet att hämta OpenTelemetry-loggaren något annorlunda. Den här informationen beskrivs ytterligare i följande exempel.
För Application Insights Java agenten:
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();
För automatisk konfiguration av 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.api.logs.Severity;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder;
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder =
AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorAutoConfigureOptions options = new AzureMonitorAutoConfigureOptions();
options.connectionString("<ConnectionString>");
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();
Om du vill generera anpassade händelser på ett tillförlitligt sätt använder du OpenTelemetry-API:et direkt. Vissa loggningsramverk har inte stöd för att lägga till eller parsa attributet anpassade händelser.
Det går inte att skicka ett customEvent med attributet "microsoft.custom_event.name" i Java internt.
Om du vill skicka en customEvent med logger.emit, anger du attributet "microsoft.custom_event.name" i loggobjektet attributes. Andra attribut kan också inkluderas efter behov.
Skicka anpassade händelser
export class CustomEventSample {
static async run() {
// Import the Microsoft OpenTelemetry Distro and the OpenTelemetry logs API
const { useMicrosoftOpenTelemetry } = await import("@microsoft/opentelemetry");
const { logs, SeverityNumber } = await import("@opentelemetry/api-logs");
// Initialize the Microsoft OpenTelemetry Distro with logging enabled
useMicrosoftOpenTelemetry({
azureMonitor: {},
});
// 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");
}
}
Om du vill skicka ett customEvent i Python använder du loggningsbiblioteket med attributet "microsoft.custom_event.name" i parametern extra.
Skicka anpassade händelser
import logging
from microsoft.opentelemetry import use_microsoft_opentelemetry
# Set up your application logger
logger = logging.getLogger("my-app-logger")
# Configure Azure Monitor to collect logs from the specified logger name
use_microsoft_opentelemetry(
enable_azure_monitor=True,
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"
},
)
Ändra telemetri
I det här avsnittet beskrivs hur du ändrar telemetri.
Lägga till span-attribut
Dessa attribut kan inkludera att lägga till en anpassad egenskap i din telemetri. Du kan också använda attribut för att ange valfria fält i Application Insights-schemat, till exempel klient-IP.
Lägga till en anpassad egenskap till en Span
Alla attribut som du lägger till i intervall exporteras som anpassade egenskaper. De fyller i fältet customDimensions i tabellen begäranden, beroenden, spårningar eller undantag.
Om du vill lägga till span-attribut använder du något av följande två sätt:
Tips
Fördelen med att använda alternativ som tillhandahålls av instrumentationsbibliotek, när de är tillgängliga, är att hela kontexten är tillgänglig. Därför kan användarna välja att lägga till eller filtrera fler attribut. Till exempel ger berika-alternativet i instrumentationsbiblioteket HttpClient användare access till HttpRequestMessage och HttpResponseMessage. De kan välja vad som helst från den och lagra den som ett attribut.
Många instrumentationsbibliotek ger ett berikande alternativ. Vägledning finns i readme-filerna för enskilda instrumentationsbibliotek:
Använd en anpassad processor:
Tips
Lägg till processorn som visas här före lägga till Azure Monitor.
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry.Trace;
// 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()));
// Configure the Microsoft OpenTelemetry Distro. This service will collect
// and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseMicrosoftOpenTelemetry(options =>
options.Exporters = ExportTarget.AzureMonitor);
// Build the ASP.NET Core application.
var app = builder.Build();
// Start the ASP.NET Core application.
app.Run();
Lägg till ActivityEnrichingProcessor.cs till din project med följande kod:
using System.Diagnostics;
using OpenTelemetry;
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");
}
}
Om du vill lägga till span-attribut använder du något av följande två sätt:
- Använd alternativ som tillhandahålls av instrumentationsbibliotek.
- Lägg till en anpassad span-processor.
Tips
Fördelen med att använda alternativ som tillhandahålls av instrumentationsbibliotek, när de är tillgängliga, är att hela kontexten är tillgänglig. Därför kan användarna välja att lägga till eller filtrera fler attribut. Till exempel ger berika-alternativet i instrumentationsbiblioteket HttpClient användare access till själva httpRequestMessage. De kan välja vad som helst från den och lagra den som ett attribut.
Många instrumentationsbibliotek ger ett berikande alternativ. Vägledning finns i readme-filerna för enskilda instrumentationsbibliotek:
Använd en anpassad processor:
Tips
Lägg till processorn som visas här före Azure Monitor Exporter.
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry;
using OpenTelemetry.Trace;
// Create the SDK and keep its providers alive until application shutdown.
using var sdk = OpenTelemetrySdk.Create(telemetry =>
{
telemetry.WithTracing(tracing => tracing
// Collect spans from the application activity source.
.AddSource("OTel.AzureMonitor.Demo")
// Run the custom processor before exporting spans.
.AddProcessor(new ActivityEnrichingProcessor()))
// Configure the Microsoft OpenTelemetry Distro.
.UseMicrosoftOpenTelemetry(options =>
options.Exporters = ExportTarget.AzureMonitor);
});
Lägg till ActivityEnrichingProcessor.cs till din project med följande kod:
using System.Diagnostics;
using OpenTelemetry;
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");
}
}
Du kan använda opentelemetry-api för att lägga till attribut i intervall.
Om du lägger till ett eller flera span-attribut customDimensions fylls fältet i tabellen requests, dependencies, traceseller exceptions .
Lägg till opentelemetry-api-1.0.0.jar (eller senare) i ditt program:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Lägg till anpassade dimensioner i koden:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
Lägg till anpassade dimensioner i koden:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
Lägg till anpassade egenskaper för span
export class SpanAttributeEnrichmentSample {
static async run() {
// Import the Microsoft OpenTelemetry Distro
const { useMicrosoftOpenTelemetry } = await import("@microsoft/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 the Microsoft OpenTelemetry Distro with the custom processor
useMicrosoftOpenTelemetry({
azureMonitor: {},
spanProcessors: [new SpanEnrichingProcessor()],
});
console.log("Span enrichment processor registered");
}
}
Spara processorn som visas härnäst som span_enriching_processor.pyoch registrera den sedan:
...
# Import the necessary packages.
from microsoft.opentelemetry import use_microsoft_opentelemetry
from opentelemetry import trace
from span_enriching_processor import SpanEnrichingProcessor
# Create a SpanEnrichingProcessor instance.
spanEnrichProcessor = SpanEnrichingProcessor()
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
use_microsoft_opentelemetry(
enable_azure_monitor=True,
azure_monitor_connection_string="<ConnectionString>",
# Configure the custom span processors to include span enrich processor.
span_processors=[spanEnrichProcessor],
)
...
Använd följande kod med span_enriching_processor.py:
# Import the SpanProcessor class from the opentelemetry.sdk.trace module.
from opentelemetry.sdk.trace import SpanProcessor
class SpanEnrichingProcessor(SpanProcessor):
def on_start(self, span, parent_context=None):
# Prefix the span name with the string "Updated-".
span.update_name("Updated-" + span.name)
# Add the custom dimension "CustomDimension1" with the value "Value1".
span.set_attribute("CustomDimension1", "Value1")
# Add the custom dimension "CustomDimension2" with the value "Value2".
span.set_attribute("CustomDimension2", "Value2")
Ange användarens IP-adress
Du kan fylla i fältet client_IP för begäranden genom att ange ett attribut för spannet. Application Insights använder IP-adressen för att generera attribut för användarplatser och tar sedan bort den som standard.
Använd exemplet med anpassad egenskap, men ersätt följande kodrader i 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", "<IpAddress>");
Använd exemplet med anpassad egenskap, men ersätt följande kodrader i 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", "<IpAddress>");
Java fyller i fältet automatiskt.
Det här fältet fylls i automatiskt.
Använd exemplet med anpassad egenskap, men ersätt följande kodrader:
Ange användarens IP-adress
export class SetUserIpSample {
static async run() {
// Import the Microsoft OpenTelemetry Distro and tracing API
const { useMicrosoftOpenTelemetry } = await import("@microsoft/opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize the Microsoft OpenTelemetry Distro
useMicrosoftOpenTelemetry({
azureMonitor: {},
});
// 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("<IpAddress>") from within your web framework's request
// pipeline
console.log(
"Use setIpForRequest('<IpAddress>') inside your request handler " +
"to stamp the active span.",
);
}
}
Använd exemplet med anpassad egenskap, men ersätt följande kodrader i SpanEnrichingProcessor.py:
# Set the `http.client_ip` attribute of the span to the specified IP address.
span.set_attribute("http.client_ip", "<IpAddress>")
Ange användar-ID eller autentiserat användar-ID
Du kan fylla i user_Id-fältet eller user_AuthenticatedId i begäranden med hjälp av följande vägledning. Användar-ID är en anonym användaridentifierare. Autentiserat användar-ID är en känd användaridentifierare.
Viktigt!
Läs gällande sekretesslagar innan du anger autentiserat användar-ID.
Använd exemplet med anpassad egenskap:
// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<UserId>");
Använd exemplet med anpassad egenskap:
// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<UserId>");
Fyll i fältet user ID i tabellen requests, dependencieseller exceptions .
Lägg till opentelemetry-api-1.0.0.jar (eller senare) i ditt program:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Ange user_Id i koden:
import io.opentelemetry.api.trace.Span;
// (user_AuthenticatedId)
Span.current().setAttribute("enduser.id", "<AuthenticatedUserId>");
// (user_Id)
Span.current().setAttribute("enduser.pseudo.id", "<AnonymousUserId>");
Fyll i fältet user ID i tabellen requests, dependencieseller exceptions .
Ange user_Id i koden:
import io.opentelemetry.api.trace.Span;
// (user_AuthenticatedId)
Span.current().setAttribute("enduser.id", "<AuthenticatedUserId>");
// (user_Id)
Span.current().setAttribute("enduser.pseudo.id", "<AnonymousUserId>");
Använd exemplet med anpassad egenskap, men ersätt följande kodrader:
Ange användaridentifierare för det aktiva spannet
export class SetUserIdSample {
static async run() {
// Import the Microsoft OpenTelemetry Distro and tracing API
const { useMicrosoftOpenTelemetry } = await import("@microsoft/opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize the Microsoft OpenTelemetry Distro
useMicrosoftOpenTelemetry({
azureMonitor: {},
});
// 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) {
// user_AuthenticatedId
span.setAttribute("enduser.id", authenticatedId);
}
if (anonymousId) {
span.setAttribute("enduser.pseudo.id", anonymousId); // user_Id
}
}
};
// Call setUserForRequest("<AuthenticatedUserId>", "<AnonymousUserId>") inside
// your request handler
console.log(
"Use setUserForRequest('<AuthenticatedUserId>', '<AnonymousUserId>') " +
"inside your request handler to stamp the active span.",
);
}
}
Använd exemplet med anpassad egenskap, men ersätt följande kodrader:
# Set the `enduser.id` attribute of the span to the specified user ID.
span.set_attribute("enduser.id", "<UserId>")
Lägga till loggattribut
OpenTelemetry använder .NET ILogger.
Det går att koppla anpassade dimensioner till loggar med hjälp av en meddelandemall.
OpenTelemetry använder .NET ILogger.
Det går att koppla anpassade dimensioner till loggar med hjälp av en meddelandemall.
Logback, Log4j och java.util.logging instrumenteras automatiskt. Du kan koppla anpassade dimensioner till loggarna på följande sätt:
För inbyggda Spring Boot-program instrumenteras Logback direkt.
export class BunyanLogAttributesSample {
static async run() {
// Import the Microsoft OpenTelemetry Distro
const { useMicrosoftOpenTelemetry } = await import("@microsoft/opentelemetry");
// Enable Azure Monitor integration and bunyan instrumentation
useMicrosoftOpenTelemetry({
azureMonitor: {},
instrumentationOptions: { bunyan: { enabled: true } },
});
const bunyanMod = await import("bunyan");
const bunyan = (bunyanMod as any).default ?? bunyanMod;
// 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");
}
}
biblioteket Python logging är autoinstrumented. Du kan koppla anpassade dimensioner till dina loggar genom att skicka en ordlista till argumentet för extra dina loggar:
...
# Create a warning log message with the properties "key1" and "value1".
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
Åsidosätt begärans felstatus för HTTP 4xx-svar
Du kan förhindra att Application Insights räknar 4xx-svar som fel.
Följande kod visar en anpassad aktivitetsprocessor som markerar HTTP 4xx-svar som lyckade.
Processor:
using System.Diagnostics;
using OpenTelemetry;
public class Http4xxSuccessProcessor : BaseProcessor<Activity>
{
public override void OnEnd(Activity activity)
{
if (activity.Kind == ActivityKind.Server)
{
var statusCodeTag = activity.GetTagItem("http.response.status_code");
if (statusCodeTag is int statusCode && statusCode >= 400 && statusCode < 500)
{
// Set status to Ok to bypass the Azure Monitor exporter's default logic
// which treats any HTTP 4xx as failure when status is Unset.
// The response code tag (e.g., 400) remains unchanged — only the
// success field in Application Insights is affected.
activity.SetStatus(ActivityStatusCode.Ok);
}
}
base.OnEnd(activity);
}
}
Registrering:
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry.Trace;
// Create the application builder.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenTelemetry()
.WithTracing(tracing => tracing.AddProcessor<Http4xxSuccessProcessor>())
// Configure the Microsoft OpenTelemetry Distro.
.UseMicrosoftOpenTelemetry(options =>
{
options.Exporters = ExportTarget.AzureMonitor;
// Set the connection string for Azure Monitor export.
options.AzureMonitor.ConnectionString = "<ConnectionString>";
});
// Build the application with the configured telemetry services.
var app = builder.Build();
// Run the application and its telemetry providers.
app.Run();
Följande kod är för en anpassad aktivitetsprocessor som markerar HTTP 4xx-svar som lyckade.
Processor:
using System.Diagnostics;
using OpenTelemetry;
public class Http4xxSuccessProcessor : BaseProcessor<Activity>
{
public override void OnEnd(Activity activity)
{
if (activity.Kind == ActivityKind.Server)
{
var statusCodeTag = activity.GetTagItem("http.response.status_code");
if (statusCodeTag is int statusCode && statusCode >= 400 && statusCode < 500)
{
// Set status to Ok to bypass the Azure Monitor exporter's default logic
// which treats any HTTP 4xx as failure when status is Unset.
// The response code tag (e.g., 400) remains unchanged — only the
// success field in Application Insights is affected.
activity.SetStatus(ActivityStatusCode.Ok);
}
}
base.OnEnd(activity);
}
}
Registrering:
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using System.Diagnostics;
using OpenTelemetry;
using OpenTelemetry.Trace;
// Create the SDK and keep its providers alive until application shutdown.
using var sdk = OpenTelemetrySdk.Create(telemetry =>
{
telemetry.WithTracing(tracing => tracing.AddProcessor(new Http4xxSuccessProcessor()))
// Configure the Microsoft OpenTelemetry Distro.
.UseMicrosoftOpenTelemetry(options =>
{
options.Exporters = ExportTarget.AzureMonitor;
// Set the connection string for Azure Monitor export.
options.AzureMonitor.ConnectionString = "<ConnectionString>";
});
});
Kommentar
Den här funktionen är tillgänglig från och med Java agentversion 3.3.0.
Som standardinställning samlar agenten in HTTP-serverbegäranden som resulterar i 4xx-svarskoder som fel. Du kan ändra detta beteende för att registrera dem som framgångar.
{
"preview": {
"captureHttpServer4xxAsError": false
}
}
Processor:
Åsidosätt felstatus för begäran för HTTP 4xx-svar
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.api.trace.StatusCode;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.trace.ReadWriteSpan;
import io.opentelemetry.sdk.trace.ReadableSpan;
import io.opentelemetry.sdk.trace.internal.ExtendedSpanProcessor;
import java.util.Set;
public class Http4xxAsSuccessProcessor implements ExtendedSpanProcessor {
private static final AttributeKey<Long> HTTP_RESPONSE_STATUS_CODE =
AttributeKey.longKey("http.response.status_code");
// Deprecated semconv attribute that some libraries may still emit
private static final AttributeKey<Long> HTTP_STATUS_CODE =
AttributeKey.longKey("http.status_code");
private static final AttributeKey<Boolean> MODIFIED_FLAG =
AttributeKey.booleanKey("ai.modified.http4xx.success");
private final Set<Long> keepAsFailure = Set.of(429L);
@Override
public void onStart(Context parentContext, ReadWriteSpan span) {
// No-op
}
@Override
public boolean isStartRequired() {
return false;
}
@Override
public void onEnding(ReadWriteSpan span) {
if (span.getKind() != SpanKind.SERVER) {
return;
}
Long statusCode = span.getAttribute(HTTP_RESPONSE_STATUS_CODE);
if (statusCode == null) {
statusCode = span.getAttribute(HTTP_STATUS_CODE);
}
if (statusCode != null
&& statusCode >= 400
&& statusCode < 500
&& !keepAsFailure.contains(statusCode)) {
// Keep the HTTP status code attribute unchanged, but mark the span as OK
// so downstream backends such as Application Insights don't count it as a
// failure.
span.setStatus(StatusCode.OK);
span.setAttribute(MODIFIED_FLAG, true);
}
}
@Override
public boolean isOnEndingRequired() {
return true;
}
@Override
public void onEnd(ReadableSpan span) {
// No-op
}
@Override
public boolean isEndRequired() {
return false;
}
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
}
@Override
public CompletableResultCode forceFlush() {
return CompletableResultCode.ofSuccess();
}
}
Registrering (Spring Boot):
import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigure;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder;
public class TelemetryConfiguration {
public static OpenTelemetry configureOpenTelemetry() {
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder =
AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorAutoConfigure.customize(sdkBuilder, "<ConnectionString>");
sdkBuilder.addTracerProviderCustomizer(
(tracerProviderBuilder, configProperties) ->
tracerProviderBuilder.addSpanProcessor(new Http4xxAsSuccessProcessor())
);
return sdkBuilder.build().getOpenTelemetrySdk();
}
}
Registrering (Quarkus):
Spara den delade processorn som Http4xxAsSuccessProcessor.java och lägg sedan till den här bean i QuarkusHttp4xxAsSuccessProcessor.java:
import jakarta.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class QuarkusHttp4xxAsSuccessProcessor extends Http4xxAsSuccessProcessor {
}
Åsidosätt felstatus för begäranden för HTTP 4xx-svar
import { SpanKind, SpanStatusCode } from "@opentelemetry/api";
import { SpanProcessor, ReadableSpan } from "@opentelemetry/sdk-trace-base";
import { ATTR_HTTP_RESPONSE_STATUS_CODE } from "@opentelemetry/semantic-conventions";
// Deprecated semconv attribute; not exported from the stable entry point.
const ATTR_HTTP_STATUS_CODE = "http.status_code";
export class Http4xxAsSuccessProcessor implements SpanProcessor {
private keepAsFailure = new Set<number>(/* [429] */);
onStart(): void {}
onEnd(span: ReadableSpan): void {
if (span.kind !== SpanKind.SERVER) return;
const attrs = span.attributes;
const sc =
(attrs[ATTR_HTTP_RESPONSE_STATUS_CODE] as number | undefined) ??
(attrs[ATTR_HTTP_STATUS_CODE] as number | undefined);
if (
typeof sc === "number" &&
sc >= 400 &&
sc < 500 &&
!this.keepAsFailure.has(sc)
) {
// By onEnd the span is ended, so setStatus()/setAttribute() are no-ops.
// Directly mutate the backing fields so the exporter sees the change.
(span as any).status = { code: SpanStatusCode.OK };
(span as any).attributes = {
...attrs,
"ai.modified.http4xx.success": true,
};
console.log(`[Processor] Rewrote ${sc} span to OK`);
}
}
shutdown(): Promise<void> {
return Promise.resolve();
}
forceFlush(): Promise<void> {
return Promise.resolve();
}
}
Processor:
Åsidosätt felstatus för begäranden för HTTP 4xx-svar
from __future__ import annotations
from typing import Iterable, Optional
from opentelemetry.trace import SpanKind, Status, StatusCode
from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor
# Current HTTP semconv attribute
ATTR_HTTP_RESPONSE_STATUS_CODE = "http.response.status_code"
# Older / deprecated attribute that some instrumentations may still emit
ATTR_HTTP_STATUS_CODE = "http.status_code"
class Http4xxAsSuccessProcessor(SpanProcessor):
def __init__(self, keep_as_failure: Optional[Iterable[int]] = None) -> None:
# Example: keep 429 as a failure if you want throttling to remain visible
self._keep_as_failure = set(keep_as_failure or ())
def on_start(self, span, parent_context=None) -> None:
# No-op
return
def on_end(self, span: ReadableSpan) -> None:
if span.kind is not SpanKind.SERVER:
return
attrs = span.attributes
statusCode = attrs.get(
ATTR_HTTP_RESPONSE_STATUS_CODE,
attrs.get(ATTR_HTTP_STATUS_CODE),
)
if (
isinstance(statusCode, int)
and 400 <= statusCode < 500
and statusCode not in self._keep_as_failure
):
# ReadableSpan.status is read-only, so in current released SDKs
# we mutate the private backing field that the exporter reads.
span._status = Status(StatusCode.OK) # pylint: disable=protected-access
# Optional diagnostic marker so you can tell the processor rewrote it.
# ReadableSpan.attributes returns a read-only MappingProxyType, so we
# update the private backing store instead.
if getattr(span, "_attributes", None) is None:
span._attributes = {} # pylint: disable=protected-access
try:
span._attributes["ai.modified.http4xx.success"] = (
True # pylint: disable=protected-access
)
except TypeError:
# Fallback if the backing store is not directly writable
span._attributes = dict(
span.attributes
) # pylint: disable=protected-access
span._attributes["ai.modified.http4xx.success"] = (
True # pylint: disable=protected-access
)
def shutdown(self) -> None:
return
def force_flush(self, timeout_millis: int = 30000) -> bool:
return True
Registrering:
from microsoft.opentelemetry import use_microsoft_opentelemetry
# Initialize the Microsoft OpenTelemetry Distro with Azure Monitor export.
use_microsoft_opentelemetry(
enable_azure_monitor=True,
azure_monitor_connection_string="<ConnectionString>",
span_processors=[Http4xxAsSuccessProcessor()],
)
Hämta spårnings-ID:t eller span-ID:t
Hämta Trace ID och Span ID för det aktiva intervallet med hjälp av följande steg.
Kommentar
Klasserna Activity och ActivitySource från System.Diagnostics namnområdet representerar OpenTelemetry-begreppen Span för respektive Tracer. Det beror på att delar av OpenTelemetry-spårnings-API:et införlivas direkt i .NET-körningen. Mer information finns i Introduction to OpenTelemetry .NET Tracing API.
using System.Diagnostics;
// 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();
Kommentar
Klasserna Activity och ActivitySource från System.Diagnostics namnområdet representerar OpenTelemetry-begreppen Span för respektive Tracer. Det beror på att delar av OpenTelemetry-spårnings-API:et införlivas direkt i .NET-körningen. Mer information finns i Introduction to OpenTelemetry .NET Tracing API.
using System.Diagnostics;
// 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();
Du kan använda opentelemetry-api för att hämta spårnings-ID:t eller span-ID:t.
Lägg till opentelemetry-api-1.0.0.jar (eller senare) i ditt program:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Hämta begärans spårnings-ID och avsnitts-ID i din kod:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
Hämta begärans spårnings-ID och avsnitts-ID i din kod:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
Hämta begärans spårnings-ID och avsnitts-ID i din kod:
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);
}
}
Hämta begärans spårnings-ID och avsnitts-ID i din kod:
# Import the necessary libraries.
from opentelemetry import trace
# Get the trace ID and span ID of the current span.
traceId = trace.get_current_span().get_span_context().trace_id
spanId = trace.get_current_span().get_span_context().span_id
Samla in feedback från slutanvändare för GenAI-agenter
Samla in feedback från slutanvändare, till exempel tummen upp eller tummen ner på ett agentsvar, och skicka den till Application Insights som en anpassad händelse. Skicka feedbacken som en OpenTelemetry-loggpost med det reserverade händelsenamnet gen_ai.evaluation.result.
Attribut för feedbackhändelser
| Attribute |
Obligatoriskt |
Description |
Example |
microsoft.custom_event.name |
Ja |
Dirigerar loggposten till customEvents tabellen. Använd det reserverade händelsenamnet. |
gen_ai.evaluation.result |
gen_ai.evaluation.name |
Ja |
Identifierar utvärderingsmåttet. Använd task_completion för att ge tummen upp eller tummen ner. |
task_completion |
gen_ai.evaluation.score.value |
Ja |
Registrerar den numeriska poängen. Använd 1.0 för tummen upp eller 0.0 för tummen ner. |
1.0 |
gen_ai.evaluation.score.label |
Ja |
Anger den människoläsbara etiketten för poängvärdet; endast två värden godtas. |
pass eller fail är de enda godtagbara värdena |
gen_ai.evaluation.explanation |
No |
Ger en valfri fritextkommentering. |
Helpful response |
gen_ai.response.id |
Rekommenderad |
Korrelerar feedbacken med agentsvaret. |
resp-123 |
microsoft.gen_ai.human_evaluation.source |
Ja för Foundry-anteckningar |
Identifierar feedbackprovidern. |
end_user eller builder |
microsoft.gen_ai.evaluation.actor.type |
Ja för Foundry-anteckningar |
Identifierar utvärderingen som mänskligt skickad. |
human |
Varning
Redigera personligt identifierbar information (PII) och andra känsliga data från gen_ai.evaluation.explanation eller använd Log Analytics säkerhetsfunktioner som säkerhet på radnivå eller åtkomst på tabellnivå för att skydda data.
Skicka synpunkter
I följande exempel används Microsoft OpenTelemetry Distro för att skicka en positiv task_completion bedömning. Generera händelsen från begärandehanteraren eller annan kod som fortfarande har den ursprungliga agentinteraktionens spårningskontext.
Skicka en agentfeedbackhändelse
using System.Text.Json;
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry;
// Create the application builder.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenTelemetry()
// Configure the Microsoft OpenTelemetry Distro.
.UseMicrosoftOpenTelemetry(options =>
{
options.Exporters = ExportTarget.AzureMonitor;
// Read the environment setting before the application configuration.
options.AzureMonitor.ConnectionString =
builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"];
});
// Build the application with the configured telemetry services.
var app = builder.Build();
app.MapPost("/feedback", (ILoggerFactory loggerFactory) =>
{
var logger = loggerFactory.CreateLogger("genai-eval");
var attributes = new List<KeyValuePair<string, object?>>
{
new("microsoft.custom_event.name", "gen_ai.evaluation.result"),
new("gen_ai.evaluation.name", "task_completion"),
new("gen_ai.evaluation.score.value", 1.0),
new("gen_ai.evaluation.score.label", "pass"),
new("gen_ai.evaluation.explanation", "Helpful response"),
new("gen_ai.response.id", "resp-123"),
new("microsoft.gen_ai.human_evaluation.source", "end_user"),
new("microsoft.gen_ai.evaluation.actor.type", "human"),
new("internal_properties", JsonSerializer.Serialize(new Dictionary<string, string>
{
["gen_ai.evaluation.type"] = "boolean",
["gen_ai.evaluation.min_value"] = "0.0",
["gen_ai.evaluation.max_value"] = "1.0",
["gen_ai.evaluation.threshold"] = "1.0",
["gen_ai.evaluation.desirable_direction"] = "increase",
})),
};
logger.Log(
LogLevel.Information,
eventId: default,
state: attributes,
exception: null,
formatter: static (_, _) => "Human evaluation submitted");
return Results.Ok();
});
// Run the application and its telemetry providers.
app.Run();
Skicka en agentfeedbackhändelse
using System.Text.Json;
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry;
// Create the application host builder.
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddOpenTelemetry()
// Configure the Microsoft OpenTelemetry Distro.
.UseMicrosoftOpenTelemetry(options =>
{
options.Exporters = ExportTarget.AzureMonitor;
// Read the environment setting before the application configuration.
options.AzureMonitor.ConnectionString =
builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"];
});
// Keep the host alive until shutdown; disposal flushes pending telemetry.
using var host = builder.Build();
var logger = host.Services
.GetRequiredService<ILoggerFactory>()
.CreateLogger("genai-eval");
var attributes = new List<KeyValuePair<string, object?>>
{
new("microsoft.custom_event.name", "gen_ai.evaluation.result"),
new("gen_ai.evaluation.name", "task_completion"),
new("gen_ai.evaluation.score.value", 1.0),
new("gen_ai.evaluation.score.label", "pass"),
new("gen_ai.evaluation.explanation", "Helpful response"),
new("gen_ai.response.id", "resp-123"),
new("microsoft.gen_ai.human_evaluation.source", "end_user"),
new("microsoft.gen_ai.evaluation.actor.type", "human"),
new("internal_properties", JsonSerializer.Serialize(new Dictionary<string, string>
{
["gen_ai.evaluation.type"] = "boolean",
["gen_ai.evaluation.min_value"] = "0.0",
["gen_ai.evaluation.max_value"] = "1.0",
["gen_ai.evaluation.threshold"] = "1.0",
["gen_ai.evaluation.desirable_direction"] = "increase",
})),
};
logger.Log(
LogLevel.Information,
eventId: default,
state: attributes,
exception: null,
formatter: static (_, _) => "Human evaluation submitted");
Använd API:et OpenTelemetry Logs för att generera gen_ai.evaluation.result med attributen i föregående tabell.
Använd API:et OpenTelemetry Logs för att generera gen_ai.evaluation.result med attributen i föregående tabell.
Skicka en agentfeedbackhändelse
import { logs } from "@opentelemetry/api-logs";
// Import the distro API and supporting instrumentation types.
import { useMicrosoftOpenTelemetry } from "@microsoft/opentelemetry";
// Initialize the Microsoft OpenTelemetry Distro.
useMicrosoftOpenTelemetry({
azureMonitor: {
azureMonitorExporterOptions: {
connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING,
},
},
});
logs.getLogger("genai-eval").emit({
body: "Human evaluation submitted",
attributes: {
"microsoft.custom_event.name": "gen_ai.evaluation.result",
"gen_ai.evaluation.name": "task_completion",
"gen_ai.evaluation.score.value": 1.0,
"gen_ai.evaluation.score.label": "pass",
"gen_ai.evaluation.explanation": "Helpful response",
"gen_ai.response.id": "resp-123",
"microsoft.gen_ai.human_evaluation.source": "end_user",
"microsoft.gen_ai.evaluation.actor.type": "human",
internal_properties: JSON.stringify({
"gen_ai.evaluation.type": "boolean",
"gen_ai.evaluation.min_value": "0.0",
"gen_ai.evaluation.max_value": "1.0",
"gen_ai.evaluation.threshold": "1.0",
"gen_ai.evaluation.desirable_direction": "increase",
}),
},
});
Skicka en agentfeedbackhändelse
import json
import logging
import os
from microsoft.opentelemetry import use_microsoft_opentelemetry
# Initialize the Microsoft OpenTelemetry Distro with Azure Monitor export.
use_microsoft_opentelemetry(
enable_azure_monitor=True,
azure_monitor_connection_string=os.environ[
"APPLICATIONINSIGHTS_CONNECTION_STRING"
],
logger_name="genai-eval",
)
logger = logging.getLogger("genai-eval")
logger.setLevel(logging.INFO)
logger.info(
"Human evaluation submitted",
extra={
"microsoft.custom_event.name": "gen_ai.evaluation.result",
"gen_ai.evaluation.name": "task_completion",
"gen_ai.evaluation.score.value": 1.0,
"gen_ai.evaluation.score.label": "pass",
"gen_ai.evaluation.explanation": "Helpful response",
"gen_ai.response.id": "resp-123",
"microsoft.gen_ai.human_evaluation.source": "end_user",
"microsoft.gen_ai.evaluation.actor.type": "human",
"internal_properties": json.dumps(
{
"gen_ai.evaluation.type": "boolean",
"gen_ai.evaluation.min_value": "0.0",
"gen_ai.evaluation.max_value": "1.0",
"gen_ai.evaluation.threshold": "1.0",
"gen_ai.evaluation.desirable_direction": "increase",
}
),
},
)
Fråga efter feedback i Application Insights
Feedbackhändelser visas i customEvents tabellen med händelsenamnet gen_ai.evaluation.result. GenAI-attributen är tillgängliga som anpassade dimensioner. Använd gen_ai.response.id för att koppla samman återkopplingen med motsvarande agentsvar, spår, begäran och beroendetelemetri.
customEvents
| where name == "gen_ai.evaluation.result"
| extend
responseId = tostring(customDimensions["gen_ai.response.id"]),
score = todouble(customDimensions["gen_ai.evaluation.score.value"]),
label = tostring(customDimensions["gen_ai.evaluation.score.label"]),
source = tostring(customDimensions["microsoft.gen_ai.human_evaluation.source"]),
internalProperties = parse_json(tostring(customDimensions["internal_properties"]))
| extend evaluationType = tostring(internalProperties["gen_ai.evaluation.type"])
| project timestamp, responseId, score, label, source, evaluationType
| order by timestamp desc
Mer information finns i:
Felsökning, feedback och support
Tips
Följande avsnitt är tillgängliga i alla OpenTelemetry Distro-artiklar.
Felsökning
OpenTelemetry Återkoppling
Så här ger du feedback:
Support
Välj en flik för det språk du väljer för att identifiera supportalternativ.
- För Azure support problem öppnar du ett Azure support-ärende.
- För hjälp med felsökning, granska felsökningsstegen.
- Om du har problem med OpenTelemetry kontaktar du OpenTelemetry-communityn direkt.
- En lista över öppna problem som rör Azure Monitor Java automatisk instrumentering finns på sidan GitHub problem.
- För Azure support problem öppnar du ett Azure support-ärende.
- Om du har problem med OpenTelemetry kontaktar du OpenTelemetry-communityn direkt.
- En lista över öppna problem med inbyggda Spring Boot-program finns på sidan GitHub issues.
- En lista över öppna problem med quarkus-inbyggda program finns på sidan GitHub issues.
Kommentar
Quarkus-communityn stöder och underhåller Quarkus-tillägg. Om du vill ha hjälp använder du Quarkus community-supportkanaler. Microsoft tillhandahåller inte teknisk support för den här integreringen.
- För Azure support problem öppnar du ett Azure support-ärende.
- Om du har problem med OpenTelemetry kontaktar du JavaScript-communityn OpenTelemetry direkt.
- En lista över öppna problem som rör Azure Monitor Exporter finns på sidan GitHub issues.
Nästa steg