Następujące biblioteki instrumentacji OpenTelemetry są uwzględniane w ramach dystrybucji usługi Azure Monitor Application Szczegółowe informacje. Aby uzyskać więcej informacji, zobacz OpenTelemetry oficjalnie obsługiwane instrumentacje.
³: Domyślnie rejestrowanie jest zbierane tylko na poziomie INFO lub wyższym. Aby zmienić to ustawienie, zobacz opcje konfiguracji.
⁴: Domyślnie rejestrowanie jest zbierane tylko wtedy, gdy rejestrowanie jest wykonywane na poziomie OSTRZEŻENIA lub wyższym.
Uwaga
Dystrybucje OpenTelemetry usługi Azure Monitor obejmują mapowanie niestandardowe i logikę, aby automatycznie emitować metryki standardowe aplikacji Szczegółowe informacje.
Napiwek
Wszystkie metryki OpenTelemetry, niezależnie od tego, czy są automatycznie zbierane z bibliotek instrumentacji, czy ręcznie zbierane z kodu niestandardowego, są obecnie traktowane jako aplikacja Szczegółowe informacje "metryki niestandardowe" na potrzeby rozliczeń. Dowiedz się więcej.
Dodawanie biblioteki instrumentacji społeczności
Więcej danych można zbierać automatycznie, dołączając biblioteki instrumentacji ze społeczności OpenTelemetry.
Uwaga
Nie obsługujemy ani nie gwarantujemy jakości bibliotek instrumentacji społeczności. Aby zasugerować jeden z naszych dystrybucji, post lub up-vote w naszej społeczności opinii. Należy pamiętać, że niektóre są oparte na eksperymentalnych specyfikacjach OpenTelemetry i mogą wprowadzać przyszłe zmiany powodujące niezgodność.
Aby dodać bibliotekę społeczności, użyj ConfigureOpenTelemetryMeterProvider metod lub ConfigureOpenTelemetryTracerProvider po dodaniu pakietu nuget dla biblioteki.
W poniższym przykładzie pokazano, jak można dodać instrumentację środowiska uruchomieniowego w celu zbierania dodatkowych metryk.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add runtime instrumentation.
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddRuntimeInstrumentation());
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
W poniższym przykładzie pokazano, jak można dodać instrumentację środowiska uruchomieniowego w celu zbierania dodatkowych metryk.
// Create a new OpenTelemetry meter provider and add runtime instrumentation and the Azure Monitor metric exporter.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddRuntimeInstrumentation()
.AddAzureMonitorMetricExporter();
Nie można rozszerzyć dystrybucji języka Java za pomocą bibliotek instrumentacji społeczności. Aby poprosić o dołączenie innej biblioteki instrumentacji, otwórz problem na naszej stronie usługi GitHub. Link do naszej strony usługi GitHub można znaleźć w sekcji Następne kroki.
Inne instrumentacje OpenTelemetry są dostępne tutaj i można je dodać przy użyciu programu TraceHandler w aplikacji Szczegółowe informacje Client.
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics, trace, ProxyTracerProvider } = require("@opentelemetry/api");
// Import the OpenTelemetry instrumentation registration function and Express instrumentation
const { registerInstrumentations } = require( "@opentelemetry/instrumentation");
const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
// Get the OpenTelemetry tracer provider and meter provider
const tracerProvider = (trace.getTracerProvider() as ProxyTracerProvider).getDelegate();
const meterProvider = metrics.getMeterProvider();
// Enable Azure Monitor integration
useAzureMonitor();
// Register the Express instrumentation
registerInstrumentations({
// List of instrumentations to register
instrumentations: [
new ExpressInstrumentation(), // Express instrumentation
],
// OpenTelemetry tracer provider
tracerProvider: tracerProvider,
// OpenTelemetry meter provider
meterProvider: meterProvider
});
Aby dodać bibliotekę instrumentacji społeczności (oficjalnie nieobsługiwaną/dołączona do dystrybucji usługi Azure Monitor), możesz instrumentować bezpośrednio przy użyciu instrumentacji. Listę bibliotek instrumentacji społeczności można znaleźć tutaj.
Uwaga
Nie zaleca się ręcznego instrumentacji obsługiwanej bibliotekiinstrument() instrumentacji w połączeniu z dystrybucją configure_azure_monitor() . Nie jest to obsługiwany scenariusz i może wystąpić niepożądane zachowanie dla telemetrii.
# Import the `configure_azure_monitor()`, `SQLAlchemyInstrumentor`, `create_engine`, and `text` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
from sqlalchemy import create_engine, text
# Configure OpenTelemetry to use Azure Monitor.
configure_azure_monitor()
# Create a SQLAlchemy engine.
engine = create_engine("sqlite:///:memory:")
# SQLAlchemy instrumentation is not officially supported by this package, however, you can use the OpenTelemetry `instrument()` method manually in conjunction with `configure_azure_monitor()`.
SQLAlchemyInstrumentor().instrument(
engine=engine,
)
# Database calls using the SQLAlchemy library will be automatically captured.
with engine.connect() as conn:
result = conn.execute(text("select 'hello world'"))
print(result.all())
Zbieranie niestandardowych danych telemetrycznych
W tej sekcji opisano sposób zbierania niestandardowych danych telemetrycznych z aplikacji.
W zależności od języka i typu sygnału istnieją różne sposoby zbierania niestandardowych danych telemetrycznych, w tym:
OpenTelemetry API
Biblioteki rejestrowania/metryk specyficzne dla języka
Klasyczny interfejs API Szczegółowe informacje aplikacji
W poniższej tabeli przedstawiono obecnie obsługiwane niestandardowe typy telemetrii:
Język
Zdarzenia niestandardowe
Metryki niestandardowe
Zależności
Wyjątki
Widoki stron
Żądania
Ślady
ASP.NET Core
OpenTelemetry API
Tak
Tak
Tak
Tak
ILogger API
Tak
Klasyczny interfejs API sztucznej inteligencji
Java
OpenTelemetry API
Tak
Tak
Tak
Tak
Logback, Log4j, JUL
Tak
Tak
Metryki mikrometryczne
Tak
Klasyczny interfejs API sztucznej inteligencji
Tak
Tak
Tak
Tak
Tak
Tak
Tak
Node.js
OpenTelemetry API
Tak
Tak
Tak
Tak
Python
OpenTelemetry API
Tak
Tak
Tak
Tak
Moduł rejestrowania języka Python
Tak
Rozszerzenie zdarzeń
Tak
Tak
Uwaga
Aplikacja Szczegółowe informacje Java 3.x nasłuchuje danych telemetrycznych wysyłanych do klasycznego interfejsu API usługi Application Szczegółowe informacje. Podobnie aplikacja Szczegółowe informacje Node.js 3.x zbiera zdarzenia utworzone za pomocą klasycznego interfejsu API usługi Application Szczegółowe informacje. Ułatwia to uaktualnianie i wypełnia lukę w naszej niestandardowej obsłudze telemetrii, dopóki wszystkie niestandardowe typy telemetrii nie będą obsługiwane za pośrednictwem interfejsu API OpenTelemetry.
Dodawanie metryk niestandardowych
W tym kontekście metryki niestandardowe odwołują się do ręcznego instrumentowania kodu w celu zbierania dodatkowych metryk poza tym, co biblioteki instrumentacji OpenTelemetry automatycznie zbierają.
Interfejs API OpenTelemetry oferuje sześć metryk "instrumentów", które obejmują różne scenariusze metryk i należy wybrać prawidłowy typ agregacji podczas wizualizacji metryk w Eksploratorze metryk. To wymaganie jest prawdziwe w przypadku używania interfejsu API metryk OpenTelemetry do wysyłania metryk i używania biblioteki instrumentacji.
W poniższej tabeli przedstawiono zalecane typy agregacji dla każdego z instrumentów metryk OpenTelemetry.
OpenTelemetry Instrument
Typ agregacji usługi Azure Monitor
Licznik
Sum
Licznik asynchroniczny
Sum
Histogram
Minimalna, Maksymalna, Średnia, Suma i Liczba
Miernik asynchroniczny
Średnia
UpDownCounter
Sum
Asynchroniczne upDownCounter
Sum
Uwaga
Typy agregacji wykraczające poza to, co pokazano w tabeli, zwykle nie mają znaczenia.
Specyfikacja OpenTelemetry opisuje instrumenty i zawiera przykłady użycia każdego z nich.
Napiwek
Histogram jest najbardziej wszechstronny i najbardziej odpowiednikiem interfejsu API Application Szczegółowe informacje GetMetric Classic. Usługa Azure Monitor obecnie spłaszcza instrument histogramu do naszych pięciu obsługiwanych typów agregacji, a obsługa percentyli jest w toku. Chociaż mniej wszechstronny, inne instrumenty OpenTelemetry mają mniejszy wpływ na wydajność aplikacji.
Uruchamianie aplikacji musi subskrybować miernik według nazwy.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Element Meter musi zostać zainicjowany przy użyciu tej samej nazwy.
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new histogram metric named "FruitSalePrice".
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");
// Create a new Random object.
var rand = new Random();
// Record a few random sale prices for apples and lemons, with different colors.
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "green"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Create a new Histogram metric named "FruitSalePrice".
// This metric will track the distribution of fruit sale prices.
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");
// Create a new Random object. This object will be used to generate random sale prices.
var rand = new Random();
// Record a few random sale prices for apples and lemons, with different colors.
// Each record includes a timestamp, a value, and a set of attributes.
// The attributes can be used to filter and analyze the metric data.
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "green"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
histogram.record(1.0);
histogram.record(100.0);
histogram.record(30.0);
}
}
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the meter for the "testMeter" namespace
const meter = metrics.getMeter("testMeter");
// Create a histogram metric
let histogram = meter.createHistogram("histogram");
// Record values to the histogram metric with different tags
histogram.record(1, { "testKey": "testValue" });
histogram.record(30, { "testKey": "testValue2" });
histogram.record(100, { "testKey2": "testValue" });
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Get a meter provider and a meter with the name "otel_azure_monitor_histogram_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_histogram_demo")
# Record three values to the histogram.
histogram = meter.create_histogram("histogram")
histogram.record(1.0, {"test_key": "test_value"})
histogram.record(100.0, {"test_key2": "test_value"})
histogram.record(30.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
Uruchamianie aplikacji musi subskrybować miernik według nazwy.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Element Meter musi zostać zainicjowany przy użyciu tej samej nazwy.
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new counter metric named "MyFruitCounter".
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
// Record the number of fruits sold, grouped by name and color.
myFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(1, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(2, new("name", "apple"), new("color", "green"));
myFruitCounter.Add(5, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(4, new("name", "lemon"), new("color", "yellow"));
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Create a new counter metric named "MyFruitCounter".
// This metric will track the number of fruits sold.
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
// Record the number of fruits sold, grouped by name and color.
myFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(1, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(2, new("name", "apple"), new("color", "green"));
myFruitCounter.Add(5, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(4, new("name", "lemon"), new("color", "yellow"));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
LongCounter myFruitCounter = meter
.counterBuilder("MyFruitCounter")
.build();
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "green"));
myFruitCounter.add(5, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(4, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
}
}
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the meter for the "testMeter" namespace
const meter = metrics.getMeter("testMeter");
// Create a counter metric
let counter = meter.createCounter("counter");
// Add values to the counter metric with different tags
counter.add(1, { "testKey": "testValue" });
counter.add(5, { "testKey2": "testValue" });
counter.add(3, { "testKey": "testValue2" });
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Get a meter provider and a meter with the name "otel_azure_monitor_counter_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_counter_demo")
# Create a counter metric with the name "counter".
counter = meter.create_counter("counter")
# Add three values to the counter.
# The first argument to the `add()` method is the value to add.
# The second argument is a dictionary of dimensions.
# Dimensions are used to group related metrics together.
counter.add(1.0, {"test_key": "test_value"})
counter.add(5.0, {"test_key2": "test_value"})
counter.add(3.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
Uruchamianie aplikacji musi subskrybować miernik według nazwy.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add a meter named "OTel.AzureMonitor.Demo".
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddMeter("OTel.AzureMonitor.Demo"));
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Element Meter musi zostać zainicjowany przy użyciu tej samej nazwy.
// Get the current process.
var process = Process.GetCurrentProcess();
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new observable gauge metric named "Thread.State".
// This metric will track the state of each thread in the current process.
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));
private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
// Iterate over all threads in the current process.
foreach (ProcessThread thread in process.Threads)
{
// Create a measurement for each thread, including the thread state, process ID, and thread ID.
yield return new((int)thread.ThreadState, new("ProcessId", process.Id), new("ThreadId", thread.Id));
}
}
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Get the current process.
var process = Process.GetCurrentProcess();
// Create a new observable gauge metric named "Thread.State".
// This metric will track the state of each thread in the current process.
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
// Iterate over all threads in the current process.
foreach (ProcessThread thread in process.Threads)
{
// Create a measurement for each thread, including the thread state, process ID, and thread ID.
yield return new((int)thread.ThreadState, new("ProcessId", process.Id), new("ThreadId", thread.Id));
}
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
meter.gaugeBuilder("gauge")
.buildWithCallback(
observableMeasurement -> {
double randomNumber = Math.floor(Math.random() * 100);
observableMeasurement.record(randomNumber, Attributes.of(AttributeKey.stringKey("testKey"), "testValue"));
});
}
}
// Import the useAzureMonitor function and the metrics module from the @azure/monitor-opentelemetry and @opentelemetry/api packages, respectively.
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration.
useAzureMonitor();
// Get the meter for the "testMeter" meter name.
const meter = metrics.getMeter("testMeter");
// Create an observable gauge metric with the name "gauge".
let gauge = meter.createObservableGauge("gauge");
// Add a callback to the gauge metric. The callback will be invoked periodically to generate a new value for the gauge metric.
gauge.addCallback((observableResult: ObservableResult) => {
// Generate a random number between 0 and 99.
let randomNumber = Math.floor(Math.random() * 100);
// Set the value of the gauge metric to the random number.
observableResult.observe(randomNumber, {"testKey": "testValue"});
});
# Import the necessary packages.
from typing import Iterable
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
from opentelemetry.metrics import CallbackOptions, Observation
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Get a meter provider and a meter with the name "otel_azure_monitor_gauge_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_gauge_demo")
# Define two observable gauge generators.
# The first generator yields a single observation with the value 9.
# The second generator yields a sequence of 10 observations with the value 9 and a different dimension value for each observation.
def observable_gauge_generator(options: CallbackOptions) -> Iterable[Observation]:
yield Observation(9, {"test_key": "test_value"})
def observable_gauge_sequence(options: CallbackOptions) -> Iterable[Observation]:
observations = []
for i in range(10):
observations.append(
Observation(9, {"test_key": i})
)
return observations
# Create two observable gauges using the defined generators.
gauge = meter.create_observable_gauge("gauge", [observable_gauge_generator])
gauge2 = meter.create_observable_gauge("gauge2", [observable_gauge_sequence])
# Wait for background execution.
input()
Dodawanie wyjątków niestandardowych
Wybierz pozycję Biblioteki instrumentacji automatycznie zgłaszają wyjątki do Szczegółowe informacje aplikacji.
Można jednak ręcznie zgłaszać wyjątki poza raportem bibliotek instrumentacji.
Na przykład wyjątki przechwycone przez kod nie są zwykle zgłaszane. Możesz zgłosić je, aby zwrócić uwagę na odpowiednie środowiska, w tym sekcję błędów i kompleksowe widoki transakcji.
// 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);
}
}
Aby zarejestrować wyjątek przy użyciu polecenia ILogger:
// Create a logger using the logger factory. The logger category name is used to filter and route log messages.
var logger = loggerFactory.CreateLogger(logCategoryName);
// Try to execute some code.
try
{
throw new Exception("Test Exception");
}
catch (Exception ex)
{
// Log an error message with the exception. The log level is set to "Error" and the event ID is set to 0.
// The log message includes a template and a parameter. The template will be replaced with the value of the parameter when the log message is written.
logger.Log(
logLevel: LogLevel.Error,
eventId: 0,
exception: ex,
message: "Hello {name}.",
args: new object[] { "World" });
}
Aby zarejestrować wyjątek przy użyciu działania:
// 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);
}
}
Aby zarejestrować wyjątek przy użyciu polecenia 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" });
}
Możesz użyć opentelemetry-api polecenia , aby zaktualizować stan wyjątków zakresu i rekordów.
Dodaj opentelemetry-api-1.0.0.jar (lub nowszą) do aplikacji:
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { trace } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the tracer for the "testTracer" namespace
const tracer = trace.getTracer("testTracer");
// Start a span with the name "hello"
let span = tracer.startSpan("hello");
// Try to throw an error
try{
throw new Error("Test Error");
}
// Catch the error and record it to the span
catch(error){
span.recordException(error);
}
Zestaw SDK języka Python openTelemetry jest implementowany w taki sposób, że zgłoszone wyjątki są automatycznie przechwytywane i rejestrowane. Zobacz poniższy przykładowy kod, aby zapoznać się z przykładem tego zachowania.
# Import the necessary packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Get a tracer for the current module.
tracer = trace.get_tracer("otel_azure_monitor_exception_demo")
# Exception events
try:
# Start a new span with the name "hello".
with tracer.start_as_current_span("hello") as span:
# This exception will be automatically recorded
raise Exception("Custom exception message.")
except Exception:
print("Exception raised")
Jeśli chcesz ręcznie rejestrować wyjątki, możesz wyłączyć tę opcję w menedżerze kontekstu i użyć record_exception() jej bezpośrednio, jak pokazano w poniższym przykładzie:
...
# 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)
...
Dodawanie zakresów niestandardowych
Możesz dodać niestandardowy zakres w dwóch scenariuszach. Po pierwsze, gdy istnieje żądanie zależności, które nie jest jeszcze zbierane przez bibliotekę instrumentacji. Po drugie, jeśli chcesz modelować proces aplikacji jako zakres w widoku kompleksowej transakcji.
Klasy Activity i ActivitySource z System.Diagnostics przestrzeni nazw reprezentują odpowiednio pojęcia OpenTelemetry i SpanTracer. Można utworzyć ActivitySource bezpośrednio przy użyciu konstruktora zamiast za pomocą polecenia TracerProvider. Każda ActivitySource klasa musi być jawnie połączona TracerProvider z usługą przy użyciu polecenia AddSource(). Wynika to z faktu, że części interfejsu API śledzenia OpenTelemetry są dołączane bezpośrednio do środowiska uruchomieniowego platformy .NET. Aby dowiedzieć się więcej, zobacz Wprowadzenie do interfejsu API śledzenia platformy .NET openTelemetry.
// Define an activity source named "ActivitySourceName". This activity source will be used to create activities for all requests to the application.
internal static readonly ActivitySource activitySource = new("ActivitySourceName");
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry tracer provider to add a source named "ActivitySourceName". This will ensure that all activities created by the activity source are traced.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddSource("ActivitySourceName"));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core application.
var app = builder.Build();
// Map a GET request to the root path ("/") to the specified action.
app.MapGet("/", () =>
{
// Start a new activity named "CustomActivity". This activity will be traced and the trace data will be sent to Azure Monitor.
using (var activity = activitySource.StartActivity("CustomActivity"))
{
// your code here
}
// Return a response message.
return $"Hello World!";
});
// Start the ASP.NET Core application.
app.Run();
StartActivity wartość domyślna to ActivityKind.Internal, ale można podać dowolną inną ActivityKindwartość .
ActivityKind.Client, ActivityKind.Produceri ActivityKind.Internal są mapowane na aplikację Szczegółowe informacje dependencies.
ActivityKind.Serveri ActivityKind.Consumer są mapowane na aplikację Szczegółowe informacje requests.
Uwaga
Klasy Activity i ActivitySource z System.Diagnostics przestrzeni nazw reprezentują odpowiednio pojęcia OpenTelemetry i SpanTracer. Można utworzyć ActivitySource bezpośrednio przy użyciu konstruktora zamiast za pomocą polecenia TracerProvider. Każda ActivitySource klasa musi być jawnie połączona TracerProvider z usługą przy użyciu polecenia AddSource(). Wynika to z faktu, że części interfejsu API śledzenia OpenTelemetry są dołączane bezpośrednio do środowiska uruchomieniowego platformy .NET. Aby dowiedzieć się więcej, zobacz Wprowadzenie do interfejsu API śledzenia platformy .NET openTelemetry.
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("ActivitySourceName")
.AddAzureMonitorTraceExporter()
.Build();
// Create an activity source named "ActivitySourceName".
var activitySource = new ActivitySource("ActivitySourceName");
// Start a new activity named "CustomActivity". This activity will be traced and the trace data will be sent to Azure Monitor.
using (var activity = activitySource.StartActivity("CustomActivity"))
{
// your code here
}
StartActivity wartość domyślna to ActivityKind.Internal, ale można podać dowolną inną ActivityKindwartość .
ActivityKind.Client, ActivityKind.Produceri ActivityKind.Internal są mapowane na aplikację Szczegółowe informacje dependencies.
ActivityKind.Serveri ActivityKind.Consumer są mapowane na aplikację Szczegółowe informacje requests.
Używanie adnotacji OpenTelemetry
Najprostszym sposobem dodawania własnych zakresów jest użycie adnotacji OpenTelemetry @WithSpan .
Zakresy wypełniają requests tabele i dependencies w Szczegółowe informacje aplikacji.
Dodaj opentelemetry-instrumentation-annotations-1.32.0.jar (lub nowszą) do aplikacji:
Domyślnie zakres kończy się w tabeli o typie dependenciesInProczależności .
W przypadku metod reprezentujących zadanie w tle, które nie jest przechwytywane przez funkcję autoinstrumentacji, zalecamy zastosowanie atrybutu kind = SpanKind.SERVER@WithSpan do adnotacji, aby upewnić się, że są one wyświetlane w tabeli Application Szczegółowe informacjerequests.
Korzystanie z interfejsu API OpenTelemetry
Jeśli poprzednia adnotacja OpenTelemetry @WithSpan nie spełnia Twoich potrzeb, możesz dodać zakresy przy użyciu interfejsu API OpenTelemetry.
Dodaj opentelemetry-api-1.0.0.jar (lub nowszą) do aplikacji:
Użyj klasy , GlobalOpenTelemetry aby utworzyć element Tracer:
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = GlobalOpenTelemetry.getTracer("com.example");
Utwórz zakres, ustaw go jako bieżący, a następnie zakończ go:
Span span = tracer.spanBuilder("my first span").startSpan();
try (Scope ignored = span.makeCurrent()) {
// do stuff within the context of this
} catch (Throwable t) {
span.recordException(t);
} finally {
span.end();
}
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { trace } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the tracer for the "testTracer" namespace
const tracer = trace.getTracer("testTracer");
// Start a span with the name "hello"
let span = tracer.startSpan("hello");
// End the span
span.end();
Interfejs API OpenTelemetry może służyć do dodawania własnych zakresów, które są wyświetlane w tabelach i dependencies w requests usłudze Application Szczegółowe informacje.
W przykładzie kodu pokazano, jak użyć tracer.start_as_current_span() metody do uruchomienia, ustawić bieżący zakres i zakończyć zakres w jego kontekście.
...
# 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)
...
Domyślnie zakres znajduje się w dependencies tabeli o typie InProczależności .
Jeśli metoda reprezentuje zadanie w tle, które nie zostało jeszcze przechwycone przez funkcję autoinstrumentacji, zalecamy ustawienie atrybutukind = SpanKind.SERVER, aby upewnić się, że jest on wyświetlany w tabeli Application Szczegółowe informacjerequests.
...
# 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.
...
Wysyłanie niestandardowych danych telemetrycznych przy użyciu klasycznego interfejsu API Szczegółowe informacje aplikacji
Zalecamy używanie interfejsów API OpenTelemetry zawsze, gdy jest to możliwe, ale może wystąpić kilka scenariuszy, w których trzeba użyć klasycznego interfejsu API usługi Application Szczegółowe informacje.
Jeśli chcesz dodać zdarzenia niestandardowe lub uzyskać dostęp do interfejsu API Szczegółowe informacje aplikacji, zastąp @azure/monitor-opentelemetry pakiet pakiet pakietem applicationinsightsw wersji 3 beta. Oferuje on te same metody i interfejsy oraz cały przykładowy kod, który @azure/monitor-opentelemetry ma zastosowanie do pakietu w wersji 3 beta.
Aby wysyłać niestandardowe dane telemetryczne przy użyciu klasycznego interfejsu applicationinsights API application Szczegółowe informacje, należy użyć pakietu beta w wersji 3. (https://www.npmjs.com/package/applicationinsights/v/beta)
// Import the TelemetryClient class from the Application Insights SDK for JavaScript.
const { TelemetryClient } = require("applicationinsights");
// Create a new TelemetryClient instance.
const telemetryClient = new TelemetryClient();
Następnie użyj polecenia , TelemetryClient aby wysłać niestandardowe dane telemetryczne:
Zdarzenia
// Create an event telemetry object.
let eventTelemetry = {
name: "testEvent"
};
// Send the event telemetry object to Azure Monitor Application Insights.
telemetryClient.trackEvent(eventTelemetry);
Dzienniki
// Create a trace telemetry object.
let traceTelemetry = {
message: "testMessage",
severity: "Information"
};
// Send the trace telemetry object to Azure Monitor Application Insights.
telemetryClient.trackTrace(traceTelemetry);
Wyjątki
// Try to execute a block of code.
try {
...
}
// If an error occurs, catch it and send it to Azure Monitor Application Insights as an exception telemetry item.
catch (error) {
let exceptionTelemetry = {
exception: error,
severity: "Critical"
};
telemetryClient.trackException(exceptionTelemetry);
}
W przeciwieństwie do innych języków język Python nie ma zestawu SDK usługi Application Szczegółowe informacje. Wszystkie potrzeby monitorowania można spełnić za pomocą dystrybucji OpenTelemetry usługi Azure Monitor, z wyjątkiem wysyłania customEvents. Dopóki interfejs API zdarzeń OpenTelemetry nie zostanie ustabilizowany, użyj rozszerzenia zdarzeń usługi Azure Monitor z dystrybucją OpenTelemetry usługi Azure Monitor, aby wysłać customEvents do usługi Application Szczegółowe informacje.
Użyj interfejsu track_event API oferowanego w rozszerzeniu, aby wysłać element customEvents.
...
from azure.monitor.events.extension import track_event
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor()
# Use the track_event() api to send custom event telemetry
# Takes event name and custom dimensions
track_event("Test event", {"key1": "value1", "key2": "value2"})
input()
...
Modyfikowanie telemetrii
W tej sekcji opisano sposób modyfikowania danych telemetrycznych.
Dodawanie atrybutów zakresu
Te atrybuty mogą obejmować dodawanie właściwości niestandardowej do telemetrii. Możesz również użyć atrybutów, aby ustawić pola opcjonalne w schemacie Application Szczegółowe informacje, na przykład adres IP klienta.
Dodawanie właściwości niestandardowej do zakresu
Wszystkie atrybuty dodawane do zakresów są eksportowane jako właściwości niestandardowe. Wypełniają one pole customDimensions w tabeli żądań, zależności, śladów lub wyjątków.
Aby dodać atrybuty span, użyj jednego z następujących dwóch sposobów:
Użyj opcji udostępnianych przez biblioteki instrumentacji.
Dodaj niestandardowy procesor span.
Napiwek
Zaletą korzystania z opcji udostępnianych przez biblioteki instrumentacji, gdy są dostępne, jest to, że cały kontekst jest dostępny. W związku z tym użytkownicy mogą wybrać opcję dodawania lub filtrowania większej liczby atrybutów. Na przykład opcja wzbogacania w bibliotece instrumentacji HttpClient zapewnia użytkownikom dostęp do httpRequestMessage i samego httpResponseMessage . Mogą wybrać dowolne elementy i zapisać je jako atrybut.
Wiele bibliotek instrumentacji udostępnia opcję wzbogacania. Aby uzyskać wskazówki, zobacz pliki readme poszczególnych bibliotek instrumentacji:
Dodaj procesor pokazany tutaj przed dodaniem usługi Azure Monitor.
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry tracer provider to add a new processor named ActivityEnrichingProcessor.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddProcessor(new ActivityEnrichingProcessor()));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core application.
var app = builder.Build();
// Start the ASP.NET Core application.
app.Run();
Dodaj ActivityEnrichingProcessor.cs do projektu następujący kod:
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");
}
}
Aby dodać atrybuty span, użyj jednego z następujących dwóch sposobów:
Użyj opcji udostępnianych przez biblioteki instrumentacji.
Dodaj niestandardowy procesor span.
Napiwek
Zaletą korzystania z opcji udostępnianych przez biblioteki instrumentacji, gdy są dostępne, jest to, że cały kontekst jest dostępny. W związku z tym użytkownicy mogą wybrać opcję dodawania lub filtrowania większej liczby atrybutów. Na przykład opcja wzbogacania w bibliotece instrumentacji HttpClient zapewnia użytkownikom dostęp do samego httpRequestMessage. Mogą wybrać dowolne elementy i zapisać je jako atrybut.
Wiele bibliotek instrumentacji udostępnia opcję wzbogacania. Aby uzyskać wskazówki, zobacz pliki readme poszczególnych bibliotek instrumentacji:
Dodaj procesor pokazany tutaj przed eksporterem usługi Azure Monitor.
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
// Add a source named "OTel.AzureMonitor.Demo".
.AddSource("OTel.AzureMonitor.Demo") // Add a new processor named ActivityEnrichingProcessor.
.AddProcessor(new ActivityEnrichingProcessor()) // Add the Azure Monitor trace exporter.
.AddAzureMonitorTraceExporter() // Add the Azure Monitor trace exporter.
.Build();
Dodaj ActivityEnrichingProcessor.cs do projektu następujący kod:
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");
}
}
Możesz użyć opentelemetry-api polecenia , aby dodać atrybuty do zakresów.
Dodanie co najmniej jednego atrybutu zakresu spowoduje wypełnienie customDimensions pola w requeststabeli , dependencies, traceslub exceptions .
Dodaj opentelemetry-api-1.0.0.jar (lub nowszą) do aplikacji:
...
# Import the necessary packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Create a SpanEnrichingProcessor instance.
span_enrich_processor = SpanEnrichingProcessor()
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
# Configure the custom span processors to include span enrich processor.
span_processors=[span_enrich_processor],
)
...
Dodaj SpanEnrichingProcessor do projektu następujący kod:
# Import the SpanProcessor class from the opentelemetry.sdk.trace module.
from opentelemetry.sdk.trace import SpanProcessor
class SpanEnrichingProcessor(SpanProcessor):
def on_end(self, span):
# Prefix the span name with the string "Updated-".
span._name = "Updated-" + span.name
# Add the custom dimension "CustomDimension1" with the value "Value1".
span._attributes["CustomDimension1"] = "Value1"
# Add the custom dimension "CustomDimension2" with the value "Value2".
span._attributes["CustomDimension2"] = "Value2"
Ustawianie adresu IP użytkownika
Pole client_IP dla żądań można wypełnić, ustawiając atrybut w zakresie. Aplikacja Szczegółowe informacje używa adresu IP do generowania atrybutów lokalizacji użytkownika, a następnie odrzuca je domyślnie.
Użyj przykładu dodaj właściwość niestandardową, ale zastąp następujące wiersze kodu w pliku ActivityEnrichingProcessor.cs:
// Add the client IP address to the activity as a tag.
// only applicable in case of activity.Kind == Server
activity.SetTag("client.address", "<IP Address>");
Użyj przykładu dodaj właściwość niestandardową, ale zastąp następujące wiersze kodu w pliku ActivityEnrichingProcessor.cs:
// Add the client IP address to the activity as a tag.
// only applicable in case of activity.Kind == Server
activity.SetTag("http.client_ip", "<IP Address>");
Język Java automatycznie wypełnia to pole.
Użyj przykładu dodaj właściwość niestandardową, ale zastąp następujące wiersze kodu:
...
// Import the SemanticAttributes class from the @opentelemetry/semantic-conventions package.
const { SemanticAttributes } = require("@opentelemetry/semantic-conventions");
// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {
onEnd(span) {
// Set the HTTP_CLIENT_IP attribute on the span to the IP address of the client.
span.attributes[SemanticAttributes.HTTP_CLIENT_IP] = "<IP Address>";
}
}
Użyj przykładu dodaj właściwość niestandardową, ale zastąp następujące wiersze kodu w pliku SpanEnrichingProcessor.py:
# Set the `http.client_ip` attribute of the span to the specified IP address.
span._attributes["http.client_ip"] = "<IP Address>"
Ustawianie identyfikatora użytkownika lub uwierzytelnioowanego identyfikatora użytkownika
Możesz wypełnić pole user_Id lub user_AuthenticatedId dla żądań, korzystając z poniższych wskazówek. Identyfikator użytkownika to anonimowy identyfikator użytkownika. Uwierzytelniony identyfikator użytkownika jest znanym identyfikatorem użytkownika.
Ważne
Zanim ustawisz uwierzytelniony identyfikator użytkownika, zapoznaj się z obowiązującymi przepisami dotyczącymi ochrony prywatności.
Użyj przykładu dodaj właściwość niestandardową, ale zastąp następujące wiersze kodu:
...
// Import the SemanticAttributes class from the @opentelemetry/semantic-conventions package.
import { SemanticAttributes } from "@opentelemetry/semantic-conventions";
// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {
onEnd(span: ReadableSpan) {
// Set the ENDUSER_ID attribute on the span to the ID of the user.
span.attributes[SemanticAttributes.ENDUSER_ID] = "<User ID>";
}
}
Użyj przykładu dodaj właściwość niestandardową, ale zastąp następujące wiersze kodu:
# Set the `enduser.id` attribute of the span to the specified user ID.
span._attributes["enduser.id"] = "<User ID>"
Funkcja OpenTelemetry używa elementu . Net's ILogger.
Dołączanie wymiarów niestandardowych do dzienników można wykonać przy użyciu szablonu komunikatu.
Funkcja OpenTelemetry używa elementu . Net's ILogger.
Dołączanie wymiarów niestandardowych do dzienników można wykonać przy użyciu szablonu komunikatu.
Logback, Log4j i java.util.logging są automatycznie tworzone. Dołączanie wymiarów niestandardowych do dzienników można wykonać na następujące sposoby:
Log4j 2.0 MapMessage ( MapMessage klucz "message" jest przechwytywany jako komunikat dziennika)
Biblioteka rejestrowania języka Python jest automatycznie uruchamiana. Wymiary niestandardowe można dołączyć do dzienników, przekazując słownik do extra argumentu dzienników.
...
# Create a warning log message with the properties "key1" and "value1".
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
Filtrowanie danych telemetrycznych
Aby odfiltrować dane telemetryczne przed opuszczeniem aplikacji, możesz użyć następujących sposobów.
Dodaj procesor pokazany tutaj przed dodaniem usługi Azure Monitor.
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry tracer provider to add a new processor named ActivityFilteringProcessor.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddProcessor(new ActivityFilteringProcessor()));
// Configure the OpenTelemetry tracer provider to add a new source named "ActivitySourceName".
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddSource("ActivitySourceName"));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core application.
var app = builder.Build();
// Start the ASP.NET Core application.
app.Run();
Dodaj ActivityFilteringProcessor.cs do projektu następujący kod:
public class ActivityFilteringProcessor : BaseProcessor<Activity>
{
// The OnStart method is called when an activity is started. This is the ideal place to filter activities.
public override void OnStart(Activity activity)
{
// prevents all exporters from exporting internal activities
if (activity.Kind == ActivityKind.Internal)
{
activity.IsAllDataRequested = false;
}
}
}
Jeśli określone źródło nie zostanie jawnie dodane przy użyciu polecenia AddSource("ActivitySourceName"), żadne z działań utworzonych przy użyciu tego źródła nie zostaną wyeksportowane.
Wiele bibliotek instrumentacji udostępnia opcję filtru. Aby uzyskać wskazówki, zobacz pliki readme poszczególnych bibliotek instrumentacji:
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("OTel.AzureMonitor.Demo") // Add a source named "OTel.AzureMonitor.Demo".
.AddProcessor(new ActivityFilteringProcessor()) // Add a new processor named ActivityFilteringProcessor.
.AddAzureMonitorTraceExporter() // Add the Azure Monitor trace exporter.
.Build();
Dodaj ActivityFilteringProcessor.cs do projektu następujący kod:
public class ActivityFilteringProcessor : BaseProcessor<Activity>
{
// The OnStart method is called when an activity is started. This is the ideal place to filter activities.
public override void OnStart(Activity activity)
{
// prevents all exporters from exporting internal activities
if (activity.Kind == ActivityKind.Internal)
{
activity.IsAllDataRequested = false;
}
}
}
Jeśli określone źródło nie zostanie jawnie dodane przy użyciu polecenia AddSource("ActivitySourceName"), żadne z działań utworzonych przy użyciu tego źródła nie zostaną wyeksportowane.
Wyklucz opcję adresu URL udostępnioną przez wiele bibliotek instrumentacji HTTP.
W poniższym przykładzie pokazano, jak wykluczyć określony adres URL z śledzenia przy użyciu biblioteki instrumentacji HTTP/HTTPS:
// Import the useAzureMonitor function and the ApplicationInsightsOptions class from the @azure/monitor-opentelemetry package.
const { useAzureMonitor, ApplicationInsightsOptions } = require("@azure/monitor-opentelemetry");
// Import the HttpInstrumentationConfig class from the @opentelemetry/instrumentation-http package.
const { HttpInstrumentationConfig }= require("@opentelemetry/instrumentation-http");
// Import the IncomingMessage and RequestOptions classes from the http and https packages, respectively.
const { IncomingMessage } = require("http");
const { RequestOptions } = require("https");
// Create a new HttpInstrumentationConfig object.
const httpInstrumentationConfig: HttpInstrumentationConfig = {
enabled: true,
ignoreIncomingRequestHook: (request: IncomingMessage) => {
// Ignore OPTIONS incoming requests.
if (request.method === 'OPTIONS') {
return true;
}
return false;
},
ignoreOutgoingRequestHook: (options: RequestOptions) => {
// Ignore outgoing requests with the /test path.
if (options.path === '/test') {
return true;
}
return false;
}
};
// Create a new ApplicationInsightsOptions object.
const config: ApplicationInsightsOptions = {
instrumentationOptions: {
http: {
httpInstrumentationConfig
}
}
};
// Enable Azure Monitor integration using the useAzureMonitor function and the ApplicationInsightsOptions object.
useAzureMonitor(config);
Użyj procesora niestandardowego. Można użyć niestandardowego procesora zakresu, aby wykluczyć niektóre zakresy z eksportowanych. Aby oznaczyć zakresy, które nie mają być eksportowane, ustaw wartość TraceFlagDEFAULT.
Użyj przykładu dodaj właściwość niestandardową, ale zastąp następujące wiersze kodu:
// Import the necessary packages.
const { SpanKind, TraceFlags } = require("@opentelemetry/api");
const { ReadableSpan, Span, SpanProcessor } = require("@opentelemetry/sdk-trace-base");
// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {
forceFlush(): Promise<void> {
return Promise.resolve();
}
shutdown(): Promise<void> {
return Promise.resolve();
}
onStart(_span: Span): void {}
onEnd(span) {
// If the span is an internal span, set the trace flags to NONE.
if(span.kind == SpanKind.INTERNAL){
span.spanContext().traceFlags = TraceFlags.NONE;
}
}
}
Wyklucz adres URL ze zmienną środowiskową OTEL_PYTHON_EXCLUDED_URLS :
Spowoduje to wykluczenie punktu końcowego pokazanego w poniższym przykładzie platformy Flask:
...
# Import the Flask and Azure Monitor OpenTelemetry SDK libraries.
import flask
from azure.monitor.opentelemetry import configure_azure_monitor
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Create a Flask application.
app = flask.Flask(__name__)
# Define a route. Requests sent to this endpoint will not be tracked due to
# flask_config configuration.
@app.route("/ignore")
def ignore():
return "Request received but not tracked."
...
Użyj procesora niestandardowego. Można użyć niestandardowego procesora zakresu, aby wykluczyć niektóre zakresy z eksportowanych. Aby oznaczyć zakresy, które nie mają być eksportowane, ustaw wartość TraceFlagDEFAULT.
...
# Import the necessary libraries.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
# Configure the custom span processors to include span filter processor.
span_processors=[span_filter_processor],
)
...
Dodaj SpanFilteringProcessor do projektu następujący kod:
# Import the necessary libraries.
from opentelemetry.trace import SpanContext, SpanKind, TraceFlags
from opentelemetry.sdk.trace import SpanProcessor
# Define a custom span processor called `SpanFilteringProcessor`.
class SpanFilteringProcessor(SpanProcessor):
# Prevents exporting spans from internal activities.
def on_start(self, span, parent_context):
# Check if the span is an internal activity.
if span._kind is SpanKind.INTERNAL:
# Create a new span context with the following properties:
# * The trace ID is the same as the trace ID of the original span.
# * The span ID is the same as the span ID of the original span.
# * The is_remote property is set to `False`.
# * The trace flags are set to `DEFAULT`.
# * The trace state is the same as the trace state of the original span.
span._context = SpanContext(
span.context.trace_id,
span.context.span_id,
span.context.is_remote,
TraceFlags(TraceFlags.DEFAULT),
span.context.trace_state,
)
Pobieranie identyfikatora śledzenia lub identyfikatora zakresu
Możesz pobrać identyfikator śledzenia lub identyfikator zakresu. Jeśli dzienniki są wysyłane do miejsca docelowego innego niż aplikacja Szczegółowe informacje, rozważ dodanie identyfikatora śledzenia lub identyfikatora zakresu. Umożliwia to lepszą korelację podczas debugowania i diagnozowania problemów.
Klasy Activity i ActivitySource z System.Diagnostics przestrzeni nazw reprezentują odpowiednio pojęcia OpenTelemetry i SpanTracer. Wynika to z faktu, że części interfejsu API śledzenia OpenTelemetry są dołączane bezpośrednio do środowiska uruchomieniowego platformy .NET. Aby dowiedzieć się więcej, zobacz Wprowadzenie do interfejsu API śledzenia platformy .NET openTelemetry.
// Get the current activity.
Activity activity = Activity.Current;
// Get the trace ID of the activity.
string traceId = activity?.TraceId.ToHexString();
// Get the span ID of the activity.
string spanId = activity?.SpanId.ToHexString();
Uwaga
Klasy Activity i ActivitySource z System.Diagnostics przestrzeni nazw reprezentują odpowiednio pojęcia OpenTelemetry i SpanTracer. Wynika to z faktu, że części interfejsu API śledzenia OpenTelemetry są dołączane bezpośrednio do środowiska uruchomieniowego platformy .NET. Aby dowiedzieć się więcej, zobacz Wprowadzenie do interfejsu API śledzenia platformy .NET openTelemetry.
// Get the current activity.
Activity activity = Activity.Current;
// Get the trace ID of the activity.
string traceId = activity?.TraceId.ToHexString();
// Get the span ID of the activity.
string spanId = activity?.SpanId.ToHexString();
Możesz użyć opentelemetry-api polecenia , aby uzyskać identyfikator śledzenia lub identyfikator zakresu.
Dodaj opentelemetry-api-1.0.0.jar (lub nowszą) do aplikacji:
Pobierz identyfikator śledzenia żądania i identyfikator zakresu w kodzie:
// Import the trace module from the OpenTelemetry API.
const { trace } = require("@opentelemetry/api");
// Get the span ID and trace ID of the active span.
let spanId = trace.getActiveSpan().spanContext().spanId;
let traceId = trace.getActiveSpan().spanContext().traceId;
Pobierz identyfikator śledzenia żądania i identyfikator zakresu w kodzie:
# Import the necessary libraries.
from opentelemetry import trace
# Get the trace ID and span ID of the current span.
trace_id = trace.get_current_span().get_span_context().trace_id
span_id = trace.get_current_span().get_span_context().span_id
Aby przejrzeć kod źródłowy, zobacz repozytorium GitHub aspnetcore usługi Azure Monitor.
Aby zainstalować pakiet NuGet, sprawdź dostępność aktualizacji lub wyświetl informacje o wersji, zobacz stronę Pakiet NuGet platformy AspNetCore usługi Azure Monitor.
Aby zapoznać się z usługami Azure Monitor i OpenTelemetry, zobacz Przykładowa aplikacja usługi Azure Monitor.
Aby dowiedzieć się więcej na temat biblioteki OpenTelemetry i jej społeczności, zobacz repozytorium GitHub OpenTelemetry .NET.
Aby włączyć środowiska użycia, włącz monitorowanie użytkowników sieci Web lub przeglądarki.
Aby lepiej zapoznać się z usługą Azure Monitor Application Szczegółowe informacje i aplikacją OpenTelemetry, zobacz Przykładowa aplikacja usługi Azure Monitor.
Aby dowiedzieć się więcej o technologii OpenTelemetry i jej społeczności, zobacz repozytorium GitHub Języka JavaScript openTelemetry.
Aby włączyć środowiska użycia, włącz monitorowanie użytkowników sieci Web lub przeglądarki.
Aby zapoznać się z kodem źródłowym i dodatkową dokumentacją, zobacz repozytorium GitHub dystrybucji usługi Azure Monitor.
Aby wyświetlić dodatkowe przykłady i przypadki użycia, zobacz Przykłady dystrybucji usługi Azure Monitor.
Aby zainstalować pakiet PyPI, sprawdź aktualizacje lub wyświetl informacje o wersji, zobacz stronę Pakiet PyPI usługi Azure Monitor.
Aby lepiej zapoznać się z usługą Azure Monitor Application Szczegółowe informacje i aplikacją OpenTelemetry, zobacz Przykładowa aplikacja usługi Azure Monitor.
Aby dowiedzieć się więcej na temat biblioteki OpenTelemetry i jej społeczności, zobacz repozytorium GitHub OpenTelemetry Python.
Aby wyświetlić dostępne instrumentacje i składniki openTelemetry, zobacz repozytorium GitHub Współautor openTelemetry.
Aby włączyć środowiska użycia, włącz monitorowanie użytkowników sieci Web lub przeglądarki.
Często zadawane pytania
Ta sekcja zawiera odpowiedzi na typowe pytania.
Co to jest OpenTelemetry?
Jest to nowy standard open source umożliwiający obserwowanie. Dowiedz się więcej na stronie OpenTelemetry.
Dlaczego usługa Microsoft Azure Monitor inwestuje w rozwiązanie OpenTelemetry?
Firma Microsoft jest jednym z największych współautorów usługi OpenTelemetry.
Najważniejsze propozycje dotyczące biblioteki OpenTelemetry są neutralne dla dostawcy i zapewniają spójne interfejsy API/zestawy SDK w różnych językach.
Z biegiem czasu uważamy, że platforma OpenTelemetry umożliwi klientom usługi Azure Monitor obserwowanie aplikacji napisanych w językach poza obsługiwanymi językami. Rozszerza również typy danych, które można zbierać za pomocą bogatego zestawu bibliotek instrumentacji. Ponadto zestawy SDK OpenTelemetry są bardziej wydajne na dużą skalę niż ich poprzedniki, zestawy SDK aplikacji Szczegółowe informacje.
Co to jest "Dystrybucja opentelemetrii usługi Azure Monitor"?
Można go traktować jako cienką otokę, która łączy wszystkie składniki OpenTelemetry dla środowiska pierwszej klasy na platformie Azure. Ta otoka jest również nazywana dystrybucją w usłudze OpenTelemetry.
Dlaczego należy używać dystrybucji "Azure Monitor OpenTelemetry"?
Korzystanie z dystrybucji OpenTelemetry usługi Azure Monitor za pośrednictwem natywnej biblioteki OpenTelemetry z poziomu społeczności ma kilka zalet:
Zmniejsza nakład pracy przy włączaniu
Obsługiwane przez firmę Microsoft
Udostępnia funkcje specyficzne dla platformy Azure, takie jak:
Próbkowanie zgodne z klasycznymi zestawami SDK aplikacji Szczegółowe informacje
W duchu OpenTelemetry zaprojektowaliśmy dystrybucję tak, aby była otwarta i rozszerzalna. Możesz na przykład dodać następujące elementy:
Eksporter Protokołu OTLP (OpenTelemetry Protocol) i wysyłany jednocześnie do drugiego miejsca docelowego
Inne biblioteki instrumentacji nieuwzględniane w dystrybucji
Ponieważ dystrybucja dystrybucji zapewnia dystrybucję OpenTelemetry, dystrybucja obsługuje wszystkie elementy obsługiwane przez bibliotekę OpenTelemetry. Na przykład można dodać więcej procesorów telemetrycznych, eksporterów lub bibliotek instrumentacji, jeśli usługa OpenTelemetry je obsługuje.
Uwaga
Dystrybucja ustawia próbkator na niestandardowy przykładowy, stały współczynnik dla Szczegółowe informacje aplikacji. Można to zmienić na inny przykład, ale może to spowodować wyłączenie niektórych dołączonych możliwości dystrybucji.
Aby uzyskać więcej informacji na temat obsługiwanego przykładnika, zobacz sekcję Włączanie próbkowania w temacie Konfigurowanie usługi Azure Monitor OpenTelemetry.
W przypadku języków bez obsługiwanego autonomicznego eksportera OpenTelemetry usługa Azure Monitor OpenTelemetry Distro jest jedynym obecnie obsługiwanym sposobem korzystania z biblioteki OpenTelemetry w usłudze Azure Monitor. W przypadku języków z obsługiwanym autonomicznym eksporterem OpenTelemetry możesz użyć dystrybucji OpenTelemetry usługi Azure Monitor lub odpowiedniego autonomicznego eksportera OpenTelemetry OpenTelemetry w zależności od scenariusza telemetrii. Aby uzyskać więcej informacji, zobacz Kiedy należy używać eksportera OpenTelemetry usługi Azure Monitor?.
Jak przetestować dystrybucję opentelemetrii usługi Azure Monitor?
Czy należy używać interfejsu OpenTelemetry lub zestawu SDK usługi Application Szczegółowe informacje?
Zalecamy korzystanie z dystrybucji OpenTelemetry, chyba że wymagana jest funkcja dostępna tylko z obsługą formalną w zestawie SDK usługi Application Szczegółowe informacje.
Wdrażanie biblioteki OpenTelemetry teraz uniemożliwia przeprowadzenie migracji w późniejszym terminie.
Kiedy należy używać eksportera OpenTelemetry usługi Azure Monitor?
W przypadku ASP.NET Core, Java, Node.js i Python zalecamy użycie dystrybucji OpenTelemetry usługi Azure Monitor. Jest to jeden wiersz kodu, aby rozpocząć pracę.
W przypadku wszystkich innych scenariuszy platformy .NET, w tym klasycznych ASP.NET, aplikacji konsolowych itp., zalecamy użycie eksportera OpenTelemetry usługi Azure Monitor platformy .NET: Azure.Monitor.OpenTelemetry.Exporter.
❌ Ta funkcja jest niedostępna lub nie ma zastosowania.
Czy można używać funkcji OpenTelemetry dla przeglądarek internetowych?
Tak, ale nie zalecamy jej i platforma Azure nie obsługuje jej. Język JavaScript openTelemetry jest mocno zoptymalizowany pod kątem Node.js. Zamiast tego zalecamy użycie zestawu SDK javaScript usługi Application Szczegółowe informacje.
Kiedy można oczekiwać, że zestaw SDK OpenTelemetry będzie dostępny do użycia w przeglądarkach internetowych?
Internetowy zestaw SDK openTelemetry nie ma ustalonej osi czasu dostępności. Prawdopodobnie istnieje kilka lat od zestawu SDK przeglądarki, który jest realną alternatywą dla zestawu SDK języka JavaScript usługi Application Szczegółowe informacje.
Czy mogę przetestować metrykę OpenTelemetry w przeglądarce internetowej dzisiaj?
Piaskownica internetowa OpenTelemetry to rozwidlenie przeznaczone do działania openTelemetry w przeglądarce. Nie można jeszcze wysyłać danych telemetrycznych do usługi Application Szczegółowe informacje. Zestaw SDK nie definiuje ogólnych zdarzeń klienta.
Czy działa aplikacja Szczegółowe informacje obok agentów konkurencji, takich jak AppDynamics, DataDog i NewRelic obsługiwane?
Niektórzy klienci używają modułu zbierającego OpenTelemetry jako alternatywy dla agenta, mimo że firma Microsoft oficjalnie nie obsługuje podejścia opartego na agencie do monitorowania aplikacji. W międzyczasie społeczność open source przyczyniła się do eksportera usługi Azure Monitor modułu zbierającego openTelemetry, którego niektórzy klienci używają do wysyłania danych do usługi Azure Monitor Application Szczegółowe informacje. Nie jest to obsługiwane przez firmę Microsoft.
Jaka jest różnica między usługami OpenCensus i OpenTelemetry?
OpenCensus jest prekursorem OpenTelemetry. Firma Microsoft pomogła połączyć rozwiązania OpenTracing i OpenCensus w celu utworzenia biblioteki OpenTelemetry— jednego standardu obserwacji dla świata. Bieżący zestaw SDK języka Python zalecany w środowisku produkcyjnym dla usługi Azure Monitor jest oparty na usłudze OpenCensus. Firma Microsoft zobowiązuje się do tworzenia usługi Azure Monitor na podstawie biblioteki OpenTelemetry.