Tato příručka obsahuje pokyny k integraci a přizpůsobení instrumentace OpenTelemetry (OTel) v rámci Azure Monitor Application Insights.
Použijte distribuci Microsoft OpenTelemetry pro .NET, Node.js a Python. Java nadále používá Azure Monitor OpenTelemetry Distro a jeho agenta nebo integrace nativních imagí. Nejprve povolte OpenTelemetry pro váš jazyk. Nahraďte základní inicializaci příslušným příkladem; neinicializujte druhou distribuci nebo poskytovatele pro stejný signál.
Identifikátory balíčků Microsoft OpenTelemetry Distro a příkazy k instalaci jsou:
| Jazyk |
Package |
Instalační příkaz |
| Python |
microsoft-opentelemetry |
pip install microsoft-opentelemetry |
| Node.js |
@microsoft/opentelemetry |
npm install @microsoft/opentelemetry |
| platforma .NET |
Microsoft.OpenTelemetry |
dotnet add package Microsoft.OpenTelemetry |
Nastavte APPLICATIONINSIGHTS_CONNECTION_STRING před spuštěním příkladů, které ho nenastaví v kódu. Udržujte poskytovatele naživu po celou dobu běhu aplikace a při vypnutí vyprázdněte telemetrii do úložiště. Inicializujte instrumentaci Node.js před načtením knihoven aplikace; aplikace ESM musí předem načíst zavaděč Microsoft OpenTelemetry Distro.
Další informace o konceptech OpenTelemetry najdete v přehledu OpenTelemetry.
Knihovny zahrnuté v jednotlivých distribucích najdete v tématu Automatické shromažďování dat a detektory prostředků.
Pokud zahrnete knihovny instrumentace z komunity OpenTelemetry, můžete automaticky shromažďovat další data.
Upozornění
Nepodporujeme ani nezaručujeme kvalitu komunitních instrumentačních knihoven. Pokud ho chcete navrhnout pro naši distribuci, publikujte nebo hlasujte v naší komunitě pro zpětnou vazbu. Mějte na paměti, že některé jsou založené na experimentálních specifikacích OpenTelemetry a můžou představovat budoucí zásadní změny.
Pokud chcete přidat knihovnu komunity, po přidání balíčku NuGet pro knihovnu použijte metody ConfigureOpenTelemetryMeterProvider nebo ConfigureOpenTelemetryTracerProvider.
Následující příklad ukazuje, jak přidat instrumentaci modulu runtime pro shromažďování dalších metrik:
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();
Pokud chcete shromažďovat volitelné metriky modulu runtime v konzole nebo jiné ne hostované aplikaci, nainstalujte OpenTelemetry.Instrumentation.Runtime a rozšiřte stávající konfiguraci zprostředkovatele měřiče, jak je znázorněno. Tento krok není nutný pro základní nastavení distribuce. Neinicializujte druhou instanci sady SDK:
// 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());
});
Java agenta nemůžete rozšířit o komunitní instrumentační knihovny. Pokud chcete požádat o zahrnutí jiné knihovny instrumentace, otevřete problém na stránce GitHub.
Knihovny instrumentace komunity nemůžete používat s GraalVM Java nativními aplikacemi.
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");
}
}
Pokud chcete přidat knihovnu instrumentace komunity, instrumentujte ji přímo pomocí instrumentací. Seznam knihoven instrumentace komunity najdete na webu GitHub.
Poznámka:
Neinstrumentujte ručně podporovanou knihovnu instrumentace, kterou use_microsoft_opentelemetry() už instrumentuje. Duplikovaná instrumentace není podporovaná a může ovlivnit vaši telemetrii.
# 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())
Shromažďování vlastních telemetrických dat
Tato část vysvětluje, jak shromažďovat vlastní telemetrická data z vaší aplikace.
V závislosti na vašem jazyce a typu signálu existují různé způsoby shromažďování vlastních telemetrických dat, mezi které patří:
- OpenTelemetry API
- Knihovny protokolování/metrik pro specifické jazyky
Poznámka:
Rozhraní pro trasování API Micrometer pro Javu není podporováno.
Následující tabulka představuje aktuálně podporované vlastní typy telemetrie:
| Jazyk |
Vlastní události |
Vlastní metriky |
Závislosti |
Výjimky |
Zobrazení stránek |
Žádosti |
Trasování |
|
ASP.NET Core |
|
|
|
|
|
|
|
| OpenTelemetry API |
|
Ano |
Ano |
Ano |
|
Ano |
|
ILogger Rozhraní api |
Ano |
|
|
|
|
|
Ano |
|
|
|
|
|
|
|
|
|
Java |
|
|
|
|
|
|
|
| OpenTelemetry API |
Ano |
Ano |
Ano |
Ano |
|
Ano |
|
Logback, Log4j, JUL |
|
|
|
Ano |
|
|
Ano |
| Metriky v mikrometrech |
|
Ano |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Node.js |
|
|
|
|
|
|
|
| OpenTelemetry API |
Ano |
Ano |
Ano |
Ano |
|
Ano |
|
|
|
|
|
|
|
|
|
|
Python |
|
|
|
|
|
|
|
| OpenTelemetry API |
|
Ano |
Ano |
Ano |
|
Ano |
|
| Modul protokolování Python |
|
|
|
|
|
|
Ano |
| Rozšíření událostí |
Ano |
|
|
|
|
|
Ano |
Přidání vlastních metrik
V tomto kontextu termín vlastních metrik odkazuje na ruční instrumentaci kódu za účelem shromažďování dalších metrik nad rámec toho, co knihovny Instrumentace OpenTelemetry automaticky shromažďují. Další informace o používání metrik najdete v tématu Metriky v Application Insights.
Rozhraní Api OpenTelemetry nabízí šest "nástrojů" pro pokrytí různých scénářů metrik a při vizualizaci metrik v Průzkumníku metrik musíte vybrat správný typ agregace. Tento požadavek platí při použití rozhraní API metriky OpenTelemetry k odesílání metrik a při použití knihovny instrumentace.
Následující tabulka uvádí doporučené typy agregace pro jednotlivé nástroje metriky OpenTelemetry.
| OpenTelemetry nástroj |
Agregační typ Azure Monitor |
| Čítač |
Suma |
| Asynchronní čítač |
Suma |
| Histogram |
Minimální, Maximální, Průměr, Součet a Počet |
| Asynchronní měřidlo |
Průměr |
| UpDownCounter |
Suma |
| Asynchronní čítač nahoru/dolů |
Suma |
Upozornění
Ve většině případů nejsou jiné typy agregace smysluplné.
Specifikace OpenTelemetry popisuje nástroje a poskytuje příklady, kdy je možné jednotlivé použít.
Návod
Histogram je univerzální nástroj metriky OpenTelemetry pro zaznamenávání distribucí. Azure Monitor v současné době zplošťuje histogramový nástroj do pěti podporovaných typů agregace a probíhá práce na podpoře percentilů. I když méně všestranné, jiné nástroje OpenTelemetry mají menší vliv na výkon vaší aplikace.
Příklad histogramu
Spuštění aplikace se musí přihlásit k odběru měřiče podle názvu:
// 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();
Musí Meter být inicializován pomocí stejného názvu:
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"));
Zaznamenávání metrik histogramu
// 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);
}
}
Vložit OpenTelemetry:
Jaro
import io.opentelemetry.api.OpenTelemetry;
import org.springframework.beans.factory.annotation.Autowired;
@Autowired
OpenTelemetry openTelemetry;
Quarkus
import io.opentelemetry.api.OpenTelemetry;
import jakarta.inject.Inject;
@Inject
OpenTelemetry openTelemetry;
Vytvoření histogramu:
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);
Poznámka:
Komunita Quarkus podporuje a udržuje rozšíření Quarkus. Pokud potřebujete pomoc, použijte kanály podpory komunity Quarkus. Microsoft neposkytuje technickou podporu pro tuto integraci.
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");
}
}
Zaznamenat metriky histogramu
# 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()
Proti příklad
Spuštění aplikace se musí přihlásit k odběru měřiče podle názvu:
// 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();
Musí Meter být inicializován pomocí stejného názvu:
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"));
Metriky čítače záznamů
// 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();
}
}
Metriky čítače záznamů
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"));
}
}
Vložit OpenTelemetry:
Jaro
import io.opentelemetry.api.OpenTelemetry;
import org.springframework.beans.factory.annotation.Autowired;
@Autowired
OpenTelemetry openTelemetry;
Quarkus
import io.opentelemetry.api.OpenTelemetry;
import jakarta.inject.Inject;
@Inject
OpenTelemetry openTelemetry;
Vytvořte čítač:
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"));
Poznámka:
Komunita Quarkus podporuje a udržuje rozšíření Quarkus. Pokud potřebujete pomoc, použijte kanály podpory komunity Quarkus. Microsoft neposkytuje technickou podporu pro tuto integraci.
Metriky čítačů záznamů
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");
}
}
Metriky čítače záznamů
# 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()
Příklad měřidla
Spuštění aplikace se musí přihlásit k odběru měřiče podle názvu:
// 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();
Musí Meter být inicializován pomocí stejného názvu:
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));
}
}
Zaznamenejte pozorovatelné metriky typu gauge
// 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"));
});
}
}
Vložit OpenTelemetry:
Jaro
import io.opentelemetry.api.OpenTelemetry;
import org.springframework.beans.factory.annotation.Autowired;
@Autowired
OpenTelemetry openTelemetry;
Quarkus
import io.opentelemetry.api.OpenTelemetry;
import jakarta.inject.Inject;
@Inject
OpenTelemetry openTelemetry;
Vytvoření měřidla:
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"));
});
Poznámka:
Komunita Quarkus podporuje a udržuje rozšíření Quarkus. Pokud potřebujete pomoc, použijte kanály podpory komunity Quarkus. Microsoft neposkytuje technickou podporu pro tuto integraci.
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");
}
}
Zaznamenejte pozorovatelné metriky gauge
# 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()
Přidání vlastních výjimek
Výběr knihoven instrumentace automaticky hlásí výjimky do Application Insights.
Můžete ale chtít ručně hlásit výjimky nad rámec toho, co reportují knihovny instrumentace.
Například výjimky zachycené vaším kódem nejsou obvykle hlášeny. Můžete je chtít nahlásit, aby upoutaly pozornost v relevantních zkušenostech, včetně části selhání a zobrazení end-to-end transakcí.
Příklady .NET jsou fragmenty pro již instrumentovanou aplikaci. V příkladech aktivit použijte zaregistrovaný activitySource z Přidat vlastní spany.
Pro příklady protokolování použijte ILoggerFactory nakonfigurované v aplikaci jako loggerFactory.
Protokolovat výjimku pomocí aktivity:
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);
}
}
Protokolování výjimky pomocí 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" });
}
Protokolovat výjimku pomocí aktivity:
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);
}
}
Protokolování výjimky pomocí 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" });
}
Můžete použít opentelemetry-api k aktualizaci stavu úseku a zaznamenání výjimek.
Přidejte opentelemetry-api-1.0.0.jar (nebo novější verzi) do vaší aplikace:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Nastavení stavu error a zaznamenání výjimky v kódu:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
Nastavení stavu error a zaznamenání výjimky v kódu:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
Sada Node.js SDK exportuje ručně zaznamenané výjimky na základě úseku do Application Insights jako výjimky jenom když jsou zaznamenány na úseku nejvyšší úrovně nebo jako potomci vzdálených či interních úseků.
Zaznamenat vlastní výjimky
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 je implementován tak, aby se automaticky zachycovaly a zaznamenávaly výjimky. Příklad tohoto chování najdete v následující ukázce kódu:
# 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")
Pokud chcete zaznamenat výjimky ručně, můžete tuto možnost zakázat v rámci správce kontextu a použít record_exception() ji přímo, jak je znázorněno v následujícím příkladu:
...
# 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)
...
Přidejte vlastní rozsahy
Můžete chtít přidat vlastní rozsah ve dvou scénářích. Za prvé, pokud knihovna instrumentace ještě nesbírala závislostní požadavek. Za druhé, pokud chcete modelovat proces aplikace jako úsek v rámci zobrazení end-to-end transakcí.
Poznámka:
Třídy Activity a ActivitySource z oboru názvů System.Diagnostics představují v uvedeném pořadí koncepty Span a Tracer OpenTelemetry. Vytváříte ActivitySource přímo pomocí jeho konstruktoru místo pomocí .TracerProvider Každá třída ActivitySource musí být explicitně připojena k TracerProvider pomocí AddSource(). Je to proto, že části rozhraní API pro trasování OpenTelemetry jsou začleněny přímo do modulu runtime .NET. Další informace najdete v tématu Introduction k rozhraní OPENTelemetry .NET Tracing API.
Přidání vlastních spanů
// 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 je nastaveno na ActivityKind.Internal, ale můžete poskytnout jakékoli jiné ActivityKind.
ActivityKind.Client, ActivityKind.Producera ActivityKind.Internal jsou mapovány na Application Insights dependencies.
ActivityKind.Server a ActivityKind.Consumer jsou mapovány na application Insights requests.
Poznámka:
Třídy Activity a ActivitySource z oboru názvů System.Diagnostics představují v uvedeném pořadí koncepty Span a Tracer OpenTelemetry. Vytváříte ActivitySource přímo pomocí jeho konstruktoru místo pomocí .TracerProvider Každá třída ActivitySource musí být explicitně připojena k TracerProvider pomocí AddSource(). Je to proto, že části rozhraní API pro trasování OpenTelemetry jsou začleněny přímo do modulu runtime .NET. Další informace najdete v tématu Introduction k rozhraní 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 je nastaveno na ActivityKind.Internal, ale můžete poskytnout jakékoli jiné ActivityKind.
ActivityKind.Client, ActivityKind.Producera ActivityKind.Internal jsou mapovány na Application Insights dependencies.
ActivityKind.Server a ActivityKind.Consumer jsou mapovány na application Insights requests.
Použijte anotaci OpenTelemetry
Nejjednodušší způsob, jak přidat vlastní rozsahy, je použití anotace OpenTelemetry @WithSpan .
Tabulky requests a dependencies jsou zaplněny v Application Insights.
Přidejte opentelemetry-instrumentation-annotations-1.32.0.jar (nebo novější verzi) do vaší aplikace:
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-annotations</artifactId>
<version>1.32.0</version>
</dependency>
K vygenerování rozsahu při každém spuštění vaší metody použijte anotaci @WithSpan.
import io.opentelemetry.instrumentation.annotations.WithSpan;
@WithSpan(value = "your span name")
public void yourMethod() {
}
Ve výchozím nastavení končí rozsah v dependencies tabulce s typem InProc závislosti.
U metod představujících úlohu na pozadí, kterou autoinstrumentace nezachytí, doporučujeme použít atribut kind = SpanKind.SERVER na @WithSpan anotaci, aby se zajistilo, že se zobrazí v tabulce Application Insights requests .
Použití rozhraní OpenTelemetry API
Pokud předchozí poznámka OpenTelemetry @WithSpan nevyhovuje vašim potřebám, můžete rozsahy přidat pomocí rozhraní API OpenTelemetry.
Přidejte opentelemetry-api-1.0.0.jar (nebo novější verzi) do vaší aplikace:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
GlobalOpenTelemetry Pomocí třídy vytvořte Tracer:
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = GlobalOpenTelemetry.getTracer("com.example");
Vytvořte rozsah, nastavte ho jako aktuální a pak ho ukončete:
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();
}
Vložit OpenTelemetry:
Jaro
import io.opentelemetry.api.OpenTelemetry;
import org.springframework.beans.factory.annotation.Autowired;
@Autowired
OpenTelemetry openTelemetry;
Quarkus
import io.opentelemetry.api.OpenTelemetry;
import jakarta.inject.Inject;
@Inject
OpenTelemetry openTelemetry;
Vytvořte OpenTelemetry uvnitř instrumentované metody poté, co framework vloží Tracer:
import io.opentelemetry.api.trace.Tracer;
Tracer tracer = openTelemetry.getTracer("com.example");
Vytvořte rozsah, nastavte ho jako aktuální a pak ho ukončete:
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();
}
Poznámka:
Komunita Quarkus podporuje a udržuje rozšíření Quarkus. Pokud potřebujete pomoc, použijte kanály podpory komunity Quarkus. Microsoft neposkytuje technickou podporu pro tuto integraci.
Přidání vlastních spanů
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");
}
}
Rozhraní API OpenTelemetry lze použít k přidání vlastních úseků, které se zobrazují v tabulkách requests a dependencies v Application Insights.
Příklad kódu ukazuje, jak použít metodu tracer.start_as_current_span() ke spuštění, nastavit rozsah jako aktuální a ukončit rozsah v kontextu.
...
# 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)
...
Ve výchozím nastavení je rozsah v dependencies tabulce s typem InProczávislosti .
Pokud vaše metoda představuje úlohu na pozadí, která ještě není zachycena automatickou instruací, doporučujeme nastavit atribut kind = SpanKind.SERVER , aby se zajistilo, že se zobrazí v tabulce 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.
...
...
Odesílání vlastních událostí
Application Insights ukládá vlastní události v customEvents tabulce. Jedním ze způsobů, jak je analyzovat, filtrovat a vizualizovat, je použití Application Insights.
Pokud chcete automatizovat kolekci událostí interakce na straně klienta, můžete použít modul plug-in v sadě JavaScript SDK.
Distro Microsoft OpenTelemetry pro .NET odesílá vlastní události prostřednictvím exportéru protokolování Azure Monitor.
Pokud chcete odeslat CustomEvent pomocí ILogger, nastavte atribut "microsoft.custom_event.name" v šabloně zprávy.
// 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();
Distro Microsoft OpenTelemetry pro .NET odesílá vlastní události prostřednictvím exportéru protokolování Azure Monitor. Tento příklad konzoly používá ke správě kanálu protokolování a životnosti sady SDK .NET Generic Host.
Pokud chcete odeslat CustomEvent pomocí ILogger, nastavte atribut "microsoft.custom_event.name" v šabloně zprávy.
Odeslat vlastní události
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();
Pokud chcete odeslat customEvent s agentem Java, nastavte atribut "microsoft.custom_event.name" v záznamu protokolu OpenTelemetry.
V závislosti na tom, jestli se používá agent Application Insights Java nebo sada SDK automatické konfigurace, se způsob načtení protokolovacího nástroje OpenTelemetry mírně liší. Tento detail je podrobněji vysvětlen v následujících příkladech.
Pro agenta Java Application Insights:
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.logs.Logger;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.logs.Severity;
Logger logger = GlobalOpenTelemetry.get().getLogsBridge().get("opentelemetry-logger");
logger.logRecordBuilder()
.setAttribute(AttributeKey.stringKey("microsoft.custom_event.name"),
"test-event-name")
.setSeverity(Severity.INFO)
.emit();
Pro autokonfigurační 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();
Pokud chcete spolehlivě generovat vlastní události, použijte přímo rozhraní API OpenTelemetry. Některé logovací frameworky nepodporují připojení nebo zpracování atributu vlastních událostí.
Pomocí atributu customEvent v nativním Java není možné odeslat atribut "microsoft.custom_event.name".
Chcete-li odeslat customEvent pomocí logger.emit, nastavte "microsoft.custom_event.name" atribut v objektu attributes protokolu. Podle potřeby je možné zahrnout i další atributy.
Odesílání vlastních událostí
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");
}
}
Pokud chcete odeslat customEvent v Python, použijte knihovnu protokolování s atributem "microsoft.custom_event.name" v parametru extra.
Odeslat vlastní události
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"
},
)
Úprava telemetrie
Tato část vysvětluje, jak upravit telemetrii.
Přidání atributů span
Mezi tyto atributy může patřit přidání vlastní vlastnosti do telemetrie. Pomocí atributů můžete také nastavit volitelná pole ve schématu Application Insights, jako je IP adresa klienta.
Přidejte vlastní vlastnost do "spanu"
Všechny atributy , které přidáte do rozsahů, se exportují jako vlastní vlastnosti.
Naplní pole customDimensions v tabulce požadavků, závislostí, trasování nebo výjimek.
Pokud chcete přidat atributy span, použijte jeden z následujících dvou způsobů:
- Použijte možnosti poskytované knihovnami instrumentace.
- Přidejte vlastní span processor
Návod
Výhodou použití možností poskytovaných knihovnami instrumentace, pokud jsou k dispozici, je, že je k dispozici celý kontext. V důsledku toho mohou uživatelé vybrat přidání nebo filtrování dalších atributů. Možnost obohacení v knihovně instrumentace HttpClient například uživatelům poskytuje přístup k HttpRequestMessage a samotnému HttpResponseMessage. Můžou z něj vybrat cokoli a uložit ho jako atribut.
Mnoho nástrojových knihoven nabízí funkci obohacení. Pokyny najdete v souborech readme jednotlivých knihoven instrumentace:
Použití vlastního procesoru:
Návod
Přidejte procesor zobrazený tady před přidáním 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();
Do project přidejte ActivityEnrichingProcessor.cs následujícím kódem:
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");
}
}
Pokud chcete přidat atributy span, použijte jeden z následujících dvou způsobů:
- Použijte možnosti poskytované knihovnami instrumentace.
- Přidejte vlastní span processor
Návod
Výhodou použití možností poskytovaných knihovnami instrumentace, pokud jsou k dispozici, je, že je k dispozici celý kontext. V důsledku toho mohou uživatelé vybrat přidání nebo filtrování dalších atributů. Například možnost obohacení v knihovně instrumentace HttpClient poskytuje uživatelům přístup k samotné httpRequestMessage. Můžou z něj vybrat cokoli a uložit ho jako atribut.
Mnoho nástrojových knihoven nabízí funkci obohacení. Pokyny najdete v souborech readme jednotlivých knihoven instrumentace:
Použití vlastního procesoru:
Návod
Přidejte zde uvedený procesor před 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);
});
Do project přidejte ActivityEnrichingProcessor.cs následujícím kódem:
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");
}
}
Můžete použít opentelemetry-api k přidání atributů do rozsahů.
Přidání jednoho nebo více atributů span naplní customDimensions pole v requeststabulce , dependencies, tracesnebo exceptions tabulce.
Přidejte opentelemetry-api-1.0.0.jar (nebo novější verzi) do vaší aplikace:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Přidejte do kódu vlastní dimenze:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
Přidejte do kódu vlastní dimenze:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
Přidání vlastních vlastností spanu
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");
}
}
Uložte procesor zobrazený dál jako span_enriching_processor.pya pak ho zaregistrujte:
...
# 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],
)
...
Použijte následující kód v prvku 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")
Nastavení IP adresy uživatele
Pole client_IP pro požadavky můžete naplnit nastavením atributu na spanu. Application Insights používá IP adresu k vygenerování atributů umístění uživatele a ve výchozím nastavení ji zahodí.
Použijte ukázku vlastní vlastnosti, ale nahraďte následující řádky kódu v 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>");
Použijte ukázku vlastní vlastnosti, ale nahraďte následující řádky kódu v 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 toto pole automaticky naplní.
Toto pole se vyplní automaticky.
Použijte příklad vlastní vlastnosti, ale nahraďte následující řádky kódu:
Nastavte IP adresu uživatele
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.",
);
}
}
Použijte ukázku vlastní vlastnosti, ale nahraďte následující řádky kódu v SpanEnrichingProcessor.py:
# Set the `http.client_ip` attribute of the span to the specified IP address.
span.set_attribute("http.client_ip", "<IpAddress>")
Nastavení ID uživatele nebo ověřeného ID uživatele
Můžete vyplnit pole user_AuthenticatedId nebo user_Id pro požadavky pomocí následujících pokynů. ID uživatele je anonymní identifikátor uživatele. Ověřené ID uživatele je známý identifikátor uživatele.
Důležité
Než nastavíte ID ověřeného uživatele, obraťte se na příslušné zákony o ochraně osobních údajů.
Použijte příklad vlastní vlastnosti:
// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<UserId>");
Použijte příklad vlastní vlastnosti:
// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<UserId>");
Naplňte pole user ID v tabulce requests, tabulce dependencies nebo tabulce exceptions.
Přidejte opentelemetry-api-1.0.0.jar (nebo novější verzi) do vaší aplikace:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Nastavte user_Id v kódu:
import io.opentelemetry.api.trace.Span;
// (user_AuthenticatedId)
Span.current().setAttribute("enduser.id", "<AuthenticatedUserId>");
// (user_Id)
Span.current().setAttribute("enduser.pseudo.id", "<AnonymousUserId>");
Naplňte pole user ID v tabulce requests, tabulce dependencies nebo tabulce exceptions.
Nastavte user_Id v kódu:
import io.opentelemetry.api.trace.Span;
// (user_AuthenticatedId)
Span.current().setAttribute("enduser.id", "<AuthenticatedUserId>");
// (user_Id)
Span.current().setAttribute("enduser.pseudo.id", "<AnonymousUserId>");
Použijte příklad vlastní vlastnosti, ale nahraďte následující řádky kódu:
Nastavte identifikátory uživatelů pro aktivní span
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.",
);
}
}
Použijte příklad vlastní vlastnosti, ale nahraďte následující řádky kódu:
# Set the `enduser.id` attribute of the span to the specified user ID.
span.set_attribute("enduser.id", "<UserId>")
Přidání atributů protokolu
OpenTelemetry používá .NET ILogger.
Připojení vlastních dimenzí k protokolům lze provést pomocí šablony zprávy.
OpenTelemetry používá .NET ILogger.
Připojení vlastních dimenzí k protokolům lze provést pomocí šablony zprávy.
Logback, Log4j a java.util.logging se automaticky instrumentují. Připojení vlastních dimenzí k protokolům lze provést těmito způsoby:
U nativních aplikací Spring Boot je Logback integrovaný automaticky.
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");
}
}
Knihovna Python logging je automaticky instrumentovaná. Vlastní dimenze můžete k protokolům připojit předáním slovníku do argumentu extra protokolů:
...
# Create a warning log message with the properties "key1" and "value1".
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
Úprava stavu chyby požadavku pro odpovědi HTTP 4xx
Můžete zabránit tomu, aby Application Insights počítalo odpovědi 4xx jako chyby.
Následující kód ukazuje vlastní procesor aktivity, který označí odpovědi HTTP 4xx jako úspěšné.
Procesor:
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);
}
}
Registrace:
// 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();
Následující kód je určený pro vlastní procesor aktivit, který označuje úspěšné odpovědi HTTP 4xx.
Procesor:
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);
}
}
Registrace:
// 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>";
});
});
Poznámka:
Tato funkce je dostupná od agenta Java verze 3.3.0.
Ve výchozím nastavení agent zaznamenává požadavky serveru HTTP, které mají za následek kódy odpovědí 4xx jako chyby. Toto chování můžete změnit, abyste je zachytili jako úspěch:
{
"preview": {
"captureHttpServer4xxAsError": false
}
}
Procesor:
Přepsat stav chyby požadavku pro odpovědi HTTP 4xx
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();
}
}
Registrace (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();
}
}
Registrace (Quarkus):
Uložte sdílený procesor jako Http4xxAsSuccessProcessor.java, a pak přidejte tento bean do QuarkusHttp4xxAsSuccessProcessor.java:
import jakarta.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class QuarkusHttp4xxAsSuccessProcessor extends Http4xxAsSuccessProcessor {
}
Přepsání stavu chyby požadavku pro odpovědi HTTP 4xx
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();
}
}
Procesor:
Přepsání stavu chyby požadavku pro odpovědi HTTP 4xx
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
Registrace:
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()],
)
Získejte ID trasování nebo ID úseku
Pomocí následujícího postupu získejte Trace ID a Span ID pro aktuálně aktivní rozsah.
Poznámka:
Třídy Activity a ActivitySource z oboru názvů System.Diagnostics představují v uvedeném pořadí koncepty Span a Tracer OpenTelemetry. Je to proto, že části rozhraní API pro trasování OpenTelemetry jsou začleněny přímo do modulu runtime .NET. Další informace najdete v tématu Introduction k rozhraní 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();
Poznámka:
Třídy Activity a ActivitySource z oboru názvů System.Diagnostics představují v uvedeném pořadí koncepty Span a Tracer OpenTelemetry. Je to proto, že části rozhraní API pro trasování OpenTelemetry jsou začleněny přímo do modulu runtime .NET. Další informace najdete v tématu Introduction k rozhraní 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();
Můžete použít opentelemetry-api k získání ID sledování nebo ID rozsahu.
Přidejte opentelemetry-api-1.0.0.jar (nebo novější verzi) do vaší aplikace:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Získejte identifikátor sledování požadavku a identifikátor úseku v kódu:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
Získejte identifikátor sledování požadavku a identifikátor úseku v kódu:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
Získejte identifikátor sledování požadavku a identifikátor úseku v kódu:
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);
}
}
Získejte identifikátor sledování požadavku a identifikátor úseku v kódu:
# 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
Zachycení zpětné vazby koncových uživatelů pro agenty GenAI
Zachyťte zpětnou vazbu koncového uživatele, například palec nahoru nebo palec dolů v odpovědi agenta, a odešlete ji do Application Insights jako vlastní událost. Odešlete zpětnou vazbu jako záznam logu OpenTelemetry s vyhrazeným názvem události gen_ai.evaluation.result.
Atributy události zpětné vazby
| Attribute |
Povinné |
Description |
Example |
microsoft.custom_event.name |
Ano |
Směruje záznam protokolu do customEvents tabulky. Použijte název rezervované události. |
gen_ai.evaluation.result |
gen_ai.evaluation.name |
Ano |
Identifikuje metriku vyhodnocení. Pomocí task_completion můžete odeslat zpětnou vazbu pomocí palce nahoru nebo palce dolů. |
task_completion |
gen_ai.evaluation.score.value |
Ano |
Zaznamenává číselné skóre. Používá se 1.0 pro palec nahoru nebo 0.0 pro palec dolů. |
1.0 |
gen_ai.evaluation.score.label |
Ano |
Ukládá srozumitelný popisek skóre; přijímají se pouze dvě hodnoty. |
pass nebo fail jsou jediné přijatelné hodnoty. |
gen_ai.evaluation.explanation |
No |
Poskytuje volitelný bezplatný textový komentář. |
Helpful response |
gen_ai.response.id |
Doporučený |
Koreluje zpětnou vazbu s odpovědí agenta. |
resp-123 |
microsoft.gen_ai.human_evaluation.source |
Ano pro poznámky Foundry |
Identifikuje poskytovatele zpětné vazby. |
end_user nebo builder |
microsoft.gen_ai.evaluation.actor.type |
Ano pro poznámky Foundry |
Identifikuje hodnocení jako odeslané člověkem. |
human |
Odeslat názory
Následující příklady používají Microsoft OpenTelemetry Distro k odeslání pozitivního task_completion hodnocení. Vyvolejte událost z obslužné rutiny požadavku nebo z jiného kódu, který má stále k dispozici kontext trasování původní interakce agenta.
Odeslat událost zpětné vazby agenta
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();
Odeslání události zpětné vazby agenta
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");
Pomocí rozhraní OpenTelemetry Logs API vytvořte gen_ai.evaluation.result s atributy uvedenými v předchozí tabulce.
Pomocí rozhraní OpenTelemetry Logs API vytvořte gen_ai.evaluation.result s atributy uvedenými v předchozí tabulce.
Odeslat událost zpětné vazby agenta
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",
}),
},
});
Odeslání události zpětné vazby agenta
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",
}
),
},
)
Zpětná vazba k dotazům ve službě Application Insights
Události zpětné vazby se zobrazují v tabulce customEvents s názvem události gen_ai.evaluation.result. Atributy GenAI jsou k dispozici jako vlastní dimenze. Pomocí gen_ai.response.id připojte zpětnou vazbu k odpovídající odpovědi agenta, trasování, požadavku a telemetrii závislostí.
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
Další informace najdete tady:
Řešení potíží, zpětná vazba a podpora
Návod
Následující části jsou k dispozici ve všech článcích o distribuci OpenTelemetry.
Troubleshooting
Zpětná vazba k OpenTelemetry
Poskytnutí zpětné vazby:
Podpora
Vyberte kartu pro jazyk podle vašeho výběru a objevte možnosti podpory.
- V případě problémů s podporou Azure otevřete tiket Azure.
- V případě problémů s OpenTelemetry kontaktujte přímo komunitu OpenTelemetry .NET.
- Seznam otevřených problémů souvisejících s vývozcem Azure Monitor najdete na stránce GitHub Problémy.
- V případě problémů s podporou Azure otevřete tiket Azure.
- V případě problémů s OpenTelemetry kontaktujte přímo komunitu OpenTelemetry .NET.
- Seznam otevřených problémů souvisejících s vývozcem Azure Monitor najdete na stránce GitHub Problémy.
- V případě problémů s podporou Azure otevřete tiket Azure.
- Nápovědu k řešení potíží najdete v krocích pro řešení potíží.
- V případě problémů s OpenTelemetry kontaktujte přímo komunitu OpenTelemetry.
- Seznam otevřených problémů souvisejících s Azure Monitor Java automatickou instrumentací najdete na stránce Problémy na GitHubu.
- V případě problémů s podporou Azure otevřete tiket Azure.
- V případě problémů s OpenTelemetry kontaktujte přímo komunitu OpenTelemetry.
- Seznam otevřených problémů s nativními aplikacemi Spring Boot najdete na stránce GitHub Problémy.
- Seznam otevřených problémů s nativními aplikacemi Quarkus najdete na stránce GitHub Problémy.
Poznámka:
Komunita Quarkus podporuje a udržuje rozšíření Quarkus. Pokud potřebujete pomoc, použijte kanály podpory komunity Quarkus. Microsoft neposkytuje technickou podporu pro tuto integraci.
- V případě problémů s podporou Azure otevřete tiket Azure.
- V případě problémů s OpenTelemetry se obraťte přímo na komunitu OpenTelemetry Python.
- Seznam otevřených problémů souvisejících s Microsoft distribucí OpenTelemetry pro Python najdete v GitHub problémech.
Další kroky