Ten przewodnik zawiera instrukcje dotyczące integrowania i dostosowywania instrumentacji OpenTelemetry (OTel) w usłudze Azure Monitor Application Insights.
Aby dowiedzieć się więcej na temat pojęć związanych z platformą OpenTelemetry, zobacz Temat OpenTelemetry overview (Omówienie usługi OpenTelemetry) lub OpenTelemetry FAQ (Często zadawane pytania dotyczące platformy OpenTelemetry).
Automatyczne zbieranie danych
Dystrybucje automatycznie zbierają dane, dołączając biblioteki instrumentacji OpenTelemetry.
Dołączone biblioteki narzędziowe
Żądania
Zależności
Rejestrowanie
Aby zmniejszyć lub zwiększyć liczbę dzienników wysyłanych do usługi Azure Monitor, skonfiguruj rejestrowanie, aby ustawić odpowiedni poziom dziennika lub zastosować filtry. Na przykład możesz zdecydować się na wysyłanie tylko dzienników Warning i Error do usługi OpenTelemetry/Azure Monitor. OpenTelemetry nie kontroluje routingu ani filtrowania dzienników — to Twoja ILogger konfiguracja podejmuje te decyzje. Aby uzyskać więcej informacji na temat konfigurowania ILogger, zobacz Konfigurowanie rejestrowania.
Aby uzyskać więcej informacji na temat ILogger, zobacz Logowanie w C# i .NET oraz przykłady kodu.
Eksporter usługi Azure Monitor nie zawiera żadnych bibliotek instrumentacji.
Zależności z zestawów SDK (Software Development Kit) platformy Azure można zbierać przy użyciu poniższego przykładu kodu w celu ręcznego subskrybowania źródła.
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
// The following line subscribes to dependencies emitted from Azure SDKs
.AddSource("Azure.*")
.AddAzureMonitorTraceExporter()
.AddHttpClientInstrumentation(o => o.FilterHttpRequestMessage = (_) =>
{
// Azure SDKs create their own client span before calling the service using HttpClient
// In this case, we would see two spans corresponding to the same operation
// 1) created by Azure SDK 2) created by HttpClient
// To prevent this duplication we are filtering the span from HttpClient
// as span from Azure SDK contains all relevant information needed.
var parentActivity = Activity.Current?.Parent;
if (parentActivity != null && parentActivity.Source.Name.Equals("Azure.Core.Http"))
{
return false;
}
return true;
})
.Build();
Aby zmniejszyć lub zwiększyć liczbę dzienników wysyłanych do usługi Azure Monitor, skonfiguruj rejestrowanie, aby ustawić odpowiedni poziom dziennika lub zastosować filtry. Na przykład możesz zdecydować się na wysyłanie tylko dzienników Warning i Error do usługi OpenTelemetry/Azure Monitor. OpenTelemetry nie kontroluje routingu ani filtrowania dzienników — to Twoja ILogger konfiguracja podejmuje te decyzje. Aby uzyskać więcej informacji na temat konfigurowania ILogger, zobacz Konfigurowanie rejestrowania.
Żądania
- Użytkownicy usługi Java Message Service (JMS)
- Konsumenci platformy Kafka
- Netty
- Kwarc
- RabbitMQ
- Serwlety
- Planowanie wiosny
Uwaga
Servlet i Netty autoinstrumentation obejmują większość usług HTTP java, w tym Java EE, Jakarta EE, Spring Boot, Quarkus i Micronaut.
Zależności (plus propagacja śledzenia rozproszonego podrzędnego)
- Apache HttpClient
- Apache HttpAsyncClient
- AsyncHttpClient
- Google HttpClient
- gRPC
- java.net.HttpURLConnection
- Java 11 HttpClient
- Klient JAX-RS
- Jetty HttpClient (klient HTTP)
- JMS (Java Message Service)
- Kafka
- Klient Netty
- OkHttp
- RabbitMQ
Zależności (bez propagacji śledzenia rozproszonego podrzędnego)
- Obsługuje Cassandrę
- Obsługuje łączność z bazą danych Java (JDBC)
- Obsługuje bazę danych MongoDB (asynchronicznie i synchronicznie)
- Obsługuje usługę Redis (Lettuce i Jedis)
Metryki
- Metryki mikrometrów, w tym metryki siłownika spring boot
- Metryki rozszerzeń zarządzania Java (JMX)
Dzienniki
- Logback (w tym właściwości MDC) ¹
- Log4j (w tym właściwości kontekstu MDC/wątku) ¹
- Rejestrowanie JBoss (w tym właściwości MDC) ¹
- java.util.logging ¹
Aby zmniejszyć lub zwiększyć liczbę dzienników zbieranych przez usługę Azure Monitor, najpierw ustaw żądany poziom rejestrowania (np WARNING . lub ERROR) w bibliotece rejestrowania aplikacji.
Kolekcja domyślna
Dane telemetryczne emitowane przez następujące zestawy SDK platformy Azure są automatycznie zbierane domyślnie:
[//]: # "Azure Cosmos DB 4.22.0+ due to https://github.com/Azure/azure-sdk-for-java/pull/25571"
[//]: # "the remaining above names and links scraped from https://azure.github.io/azure-sdk/releases/latest/java.html"
[//]: # "and version synched manually against the oldest version in maven central built on azure-core 1.14.0"
[//]: # ""
[//]: # "var table = document.querySelector('#tg-sb-content > div > table')"
[//]: # "var str = ''"
[//]: # "for (var i = 1, row; row = table.rows[i]; i++) {"
[//]: # " var name = row.cells[0].getElementsByTagName('div')[0].textContent.trim()"
[//]: # " var stableRow = row.cells[1]"
[//]: # " var versionBadge = stableRow.querySelector('.badge')"
[//]: # " if (!versionBadge) {"
[//]: # " continue"
[//]: # " }"
[//]: # " var version = versionBadge.textContent.trim()"
[//]: # " var link = stableRow.querySelectorAll('a')[2].href"
[//]: # " str += '* [' + name + '](' + link + ') ' + version + '\n'"
[//]: # "}"
[//]: # "console.log(str)"
Żądania dotyczące aplikacji natywnych platformy Spring Boot
- Spring Web
- Spring Web MVC (Model-View-Controller)
- Spring WebFlux
Zależności dla aplikacji natywnych platformy Spring Boot
Metryki
Dzienniki dla aplikacji natywnych platformy Spring Boot
Aby zmniejszyć lub zwiększyć liczbę dzienników zbieranych przez usługę Azure Monitor, najpierw ustaw żądany poziom rejestrowania (np WARNING . lub ERROR) w bibliotece rejestrowania aplikacji.
W przypadku aplikacji natywnych Quartz zapoznaj się z dokumentacją Quarkus.
Poniższe biblioteki instrumentacji OpenTelemetry są uwzględniane w ramach dystrybucji usługi Azure Monitor Application Insights. Aby uzyskać więcej informacji, zobacz Zestaw Azure SDK dla języka JavaScript.
Żądania
Zależności
Dzienniki
Aby zmniejszyć lub zwiększyć liczbę dzienników zbieranych przez usługę Azure Monitor, najpierw ustaw żądany poziom rejestrowania (np WARNING . lub ERROR) w bibliotece rejestrowania aplikacji.
Instrumentacje można skonfigurować przy użyciu polecenia AzureMonitorOpenTelemetryOptions:
export class BunyanInstrumentationSample {
static async run() {
// Dynamically import Azure Monitor and Bunyan
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const bunyanMod = await import("bunyan");
const bunyan = (bunyanMod as any).default ?? bunyanMod;
// Enable Azure Monitor integration and bunyan instrumentation
const options = {
instrumentationOptions: {
bunyan: { enabled: true },
},
};
const monitor = useAzureMonitor(options);
// Emit a test log entry
const log = (bunyan as any).createLogger({ name: "testApp" });
log.info(
{
testAttribute1: "testValue1",
testAttribute2: "testValue2",
testAttribute3: "testValue3",
},
"testEvent"
);
console.log("Bunyan log emitted");
}
}
Żądania
Zależności
Dzienniki
Aby zmniejszyć lub zwiększyć liczbę dzienników zbieranych przez usługę Azure Monitor, najpierw ustaw żądany poziom rejestrowania (np WARNING . lub ERROR) w bibliotece rejestrowania aplikacji.
Przykłady użycia biblioteki rejestrowania języka Python można znaleźć w witrynie GitHub.
Dane telemetryczne emitowane przez zestawy SDK (Software Development Kit) platformy Azure są automatycznie zbierane domyślnie.
Przypisy
- ¹: Obsługuje automatyczne raportowanie nieobsłużonych/nieprzechwyconych wyjątków
- ²: Obsługuje metryki OpenTelemetry
Napiwek
Wszystkie metryki OpenTelemetry, niezależnie od tego, czy są automatycznie zbierane z bibliotek instrumentacji, czy ręcznie zbierane z niestandardowego kodowania, są obecnie traktowane jako "metryki niestandardowe" usługi Application Insights na potrzeby rozliczeń.
Dowiedz się więcej.
Więcej danych można zbierać automatycznie, dołączając biblioteki instrumentacji ze społeczności OpenTelemetry.
Uwaga
Nie wspieramy ani nie gwarantujemy jakości bibliotek instrumentacji społecznych. Aby zasugerować coś dla naszej dystrybucji, opublikuj post lub zagłosuj 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 problemy z kompatybilnością.
Aby dodać bibliotekę społeczności, najpierw dodaj pakiet NuGet dla biblioteki, a następnie użyj metod ConfigureOpenTelemetryMeterProvider lub ConfigureOpenTelemetryTracerProvider.
W poniższym przykładzie pokazano, jak można dodać instrumentację środowiska uruchomieniowego w celu zbierania dodatkowych metryk.
dotnet add package OpenTelemetry.Instrumentation.Runtime
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add runtime instrumentation.
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddRuntimeInstrumentation());
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
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ściowej. 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.
Nie można używać bibliotek instrumentacyjnych społeczności z aplikacjami natywnymi GraalVM dla Javy.
export class RegisterExpressInstrumentationSample {
static async run() {
// Dynamically import Azure Monitor and Express instrumentation
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { registerInstrumentations } = await import("@opentelemetry/instrumentation");
const { ExpressInstrumentation } = await import("@opentelemetry/instrumentation-express");
// Initialize Azure Monitor (uses env var if set)
const monitor = useAzureMonitor();
// Register the Express instrumentation
registerInstrumentations({
instrumentations: [new ExpressInstrumentation()],
});
console.log("Express instrumentation registered");
}
}
Aby dodać bibliotekę instrumentacji społeczności (która nie jest oficjalnie wspierana ani dołączona do dystrybucji usługi Azure Monitor), możesz bezpośrednio korzystać z instrumentacji. Listę bibliotek instrumentacji społeczności można znaleźć tutaj.
Uwaga
Ręczna instrumentacja obsługiwanej biblioteki instrumentacji z użyciem instrument() i dystrybucji configure_azure_monitor() nie jest zalecana. Nie jest to obsługiwany scenariusz i może wystąpić niepożądane zachowanie 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())
Narzędzia do wykrywania zasobów
Narzędzia do wykrywania zasobów odnajdują metadane środowiska podczas uruchamiania i wypełniają atrybuty zasobów OpenTelemetry, takie jak service.name, cloud.provider i cloud.resource_id. Te meta dane zasilają funkcje w usłudze Application Insights, takie jak Mapa aplikacji i łączenie obliczeń, i poprawiają korelację między śladami, metrykami i dziennikami.
Napiwek
Atrybuty zasobów opisują proces i jego środowisko. Atrybuty span opisują jedną operację. Użyj atrybutów zasobów dla właściwości na poziomie aplikacji, takich jak service.name.
Obsługiwane środowiska
| Środowisko |
Jak działa wykrywanie |
Notatki |
| Azure App Service |
SDK języka lub dystrybucja Azure Monitor odczytuje te dobrze znane zmienne środowiskowe usługi App Service oraz metadane hosta. |
Współpracuje z platformami .NET, Java, Node.js i Python, gdy korzystasz ze wskazówek w tym artykule. |
| Azure Functions |
Zobacz instrukcje dotyczące usługi Azure Functions OpenTelemetry |
Wszystkie wskazówki dotyczące usługi Azure Functions znajdują się tam. |
| Azure Virtual Machines |
Zestaw SDK języka lub dystrybucja wysyła zapytania do usługi Azure Instance Metadata Service |
Upewnij się, że maszyna wirtualna ma dostęp do punktu końcowego usługi Instance Metadata Service. |
| Azure Kubernetes Service (AKS) |
Użyj procesora k8sattributes OpenTelemetry Collector, aby dodać metadane platformy Kubernetes |
Zalecane dla wszystkich języków działających w AKS. |
| Azure Container Apps |
Detektory mapują zmienne środowiskowe i identyfikatory zasobów, gdy są dostępne |
Można również ustawić OTEL_RESOURCE_ATTRIBUTES, aby wypełnić luki. |
Instrumentacja ręczna i automatyczna
Automatyczna instrumentacja i dystrybutywy Azure Monitor umożliwiają wykrywanie zasobów podczas uruchamiania w obsługiwanych środowiskach platformy Azure.
W przypadku instalacji ręcznych można ustawić atrybuty zasobów bezpośrednio przy użyciu standardowych opcji OpenTelemetry:
# Applies to .NET (ASP.NET/ASP.NET Core), Java, Node.js, and Python
export OTEL_SERVICE_NAME="my-service"
export OTEL_RESOURCE_ATTRIBUTES="cloud.provider=azure,cloud.region=westus,cloud.resource_id=/subscriptions/<SUB>/resourceGroups/<RG>/providers/Microsoft.Web/sites/<APP>"
W programie Windows PowerShell:
$Env:OTEL_SERVICE_NAME="my-service"
$Env:OTEL_RESOURCE_ATTRIBUTES="cloud.provider=azure,cloud.region=westus,cloud.resource_id=/subscriptions/<SUB>/resourceGroups/<RG>/providers/Microsoft.Web/sites/<APP>"
Zagadnienia dotyczące przetwarzania OTLP
- Usługa Application Insights używa
service.name do uzyskania nazwy roli chmury. Wybierz stabilną nazwę dla usługi, aby uniknąć fragmentowanych węzłów na mapie aplikacji.
-
cloud.resource_id usprawnia łączenie zasobów obliczeniowych z zasobami platformy Azure. Jeśli brakuje tego atrybutu, niektóre środowiska mogą nie wyświetlać zasobu platformy Azure, który wygenerował dane.
Zbieraj niestandardowe dane telemetryczne
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
- Językowe biblioteki logowania i metryk
- Klasyczny interfejs API usługi Application Insights
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 Rdzeń |
|
|
|
|
|
|
|
| OpenTelemetry API |
|
Tak |
Tak |
Tak |
|
Tak |
|
ILogger Interfejs Programowania Aplikacji (API) |
|
|
|
|
|
|
Tak |
| Klasyczny interfejs API sztucznej inteligencji |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Jawa |
|
|
|
|
|
|
|
| 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 |
|
|
|
|
|
|
|
|
|
|
Pyton |
|
|
|
|
|
|
|
| OpenTelemetry API |
|
Tak |
Tak |
Tak |
|
Tak |
|
| Moduł rejestrowania języka Python |
|
|
|
|
|
|
Tak |
| Rozszerzenie wydarzeń |
Tak |
|
|
|
|
|
Tak |
Uwaga
Usługi Application Insights Java 3.x i Application Insights Node.js 3.x zbierają dane telemetryczne z klasycznego interfejsu API usługi Application Insights. To zachowanie upraszcza uaktualnianie i tymczasowo obsługuje telemetrię niestandardową, dopóki interfejs API OpenTelemetry nie zawiera wszystkich niestandardowych typów telemetrii.
Dodawanie metryk niestandardowych
W tym kontekście termin metryk niestandardowych odnosi się do ręcznego instrumentowania kodu w celu zbierania dodatkowych metryk poza tym, co biblioteki instrumentacji OpenTelemetry automatycznie zbierają. Aby dowiedzieć się więcej na temat korzystania z metryk, zobacz Metryki w usłudze Application Insights.
Interfejs API OpenTelemetry oferuje sześć narzędzi do pracy z metrykami, które obejmują różnorodne scenariusze metryk. Należy wybrać odpowiedni typ agregacji podczas wizualizacji metryk w narzędziu Metrics Explorer. To wymaganie ma zastosowanie podczas używania interfejsu API metryk OpenTelemetry do wysyłania danych i korzystania z biblioteki do instrumentacji.
W poniższej tabeli przedstawiono zalecane typy agregacji dla każdego z instrumentów metryk OpenTelemetry.
| Narzędzie OpenTelemetry |
Typ agregacji usługi Azure Monitor |
| Licznik |
Suma |
| Licznik asynchroniczny |
Suma |
| Histogram |
Minimalna, Maksymalna, Średnia, Suma i Liczba |
| Miernik asynchroniczny |
Średnia |
| UpDownCounter |
Suma |
| Asynchroniczny licznik góra-dół |
Suma |
Uwaga
W większości przypadków inne typy agregacji nie mają znaczenia.
Specyfikacja OpenTelemetry opisuje instrumenty i zawiera przykłady użycia każdego z nich.
Napiwek
Histogram jest najbardziej wszechstronny i najbardziej zbliżony do klasycznego interfejsu API Application Insights GetMetric. Usługa Azure Monitor obecnie spłaszcza instrument histogramu do pięciu obsługiwanych przez nas typów agregacji, a wsparcie dla percentyli jest w trakcie realizacji. Chociaż mniej wszechstronny, inne instrumenty OpenTelemetry mają mniejszy wpływ na wydajność aplikacji.
Przykład histogramu
Proces uruchamiania aplikacji musi zarejestrować się do miernika 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);
}
}
Wstrzyknij OpenTelemetry
Utwórz histogram:
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
histogram.record(1.0);
histogram.record(100.0);
histogram.record(30.0);
export class HistogramSample {
static async run() {
// Dynamically import Azure Monitor and metrics API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a histogram and record values
const meter = metrics.getMeter("testMeter");
const histogram = meter.createHistogram("histogram");
histogram.record(1, { testKey: "testValue" });
histogram.record(30, { testKey: "testValue2" });
histogram.record(100, { testKey2: "testValue" });
console.log("Histogram metrics recorded");
}
}
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
import os
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_histogram_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_histogram_demo")
# Record three values to the histogram.
histogram = meter.create_histogram("histogram")
histogram.record(1.0, {"test_key": "test_value"})
histogram.record(100.0, {"test_key2": "test_value"})
histogram.record(30.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
Kontrprzykład
Proces uruchamiania aplikacji musi zarejestrować się do miernika 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"));
}
}
Wstrzyknij OpenTelemetry
Utwórz licznik:
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
LongCounter myFruitCounter = meter.counterBuilder("MyFruitCounter")
.build();
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "green"));
myFruitCounter.add(5, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(4, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
export class CounterSample {
static async run() {
// Dynamically import Azure Monitor and metrics API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a counter and add some sample values
const meter = metrics.getMeter("otel_azure_monitor_counter_demo");
const counter = meter.createCounter("MyFruitCounter");
counter.add(1, { name: "apple", color: "red" });
counter.add(2, { name: "lemon", color: "yellow" });
counter.add(1, { name: "lemon", color: "yellow" });
counter.add(2, { name: "apple", color: "green" });
counter.add(5, { name: "apple", color: "red" });
counter.add(4, { name: "lemon", color: "yellow" });
console.log("Counter metrics recorded");
}
}
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
import os
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_counter_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_counter_demo")
# Create a counter metric with the name "counter".
counter = meter.create_counter("counter")
# Add three values to the counter.
# The first argument to the `add()` method is the value to add.
# The second argument is a dictionary of dimensions.
# Dimensions are used to group related metrics together.
counter.add(1.0, {"test_key": "test_value"})
counter.add(5.0, {"test_key2": "test_value"})
counter.add(3.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
Przykład miernika
Proces uruchamiania aplikacji musi zarejestrować się do miernika 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"));
});
}
}
Wstrzyknij OpenTelemetry
Utwórz miernik:
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
meter.gaugeBuilder("gauge")
.buildWithCallback(
observableMeasurement -> {
double randomNumber = Math.floor(Math.random() * 100);
observableMeasurement.record(randomNumber, Attributes.of(AttributeKey.stringKey("testKey"), "testValue"));
});
export class GaugeSample {
static async run() {
// Dynamically import Azure Monitor and metrics API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create an observable gauge and register a callback
const meter = metrics.getMeter("testMeter");
const gauge = meter.createObservableGauge("gauge");
gauge.addCallback((observableResult) => {
const randomNumber = Math.floor(Math.random() * 100);
observableResult.observe(randomNumber, { testKey: "testValue" });
});
console.log("Observable gauge registered");
}
}
# Import the necessary packages.
from typing import Iterable
import os
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
from opentelemetry.metrics import CallbackOptions, Observation
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_gauge_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_gauge_demo")
# Define two observable gauge generators.
# The first generator yields a single observation with the value 9.
# The second generator yields a sequence of 10 observations with the value 9 and a different dimension value for each observation.
def observable_gauge_generator(options: CallbackOptions) -> Iterable[Observation]:
yield Observation(9, {"test_key": "test_value"})
def observable_gauge_sequence(options: CallbackOptions) -> Iterable[Observation]:
observations = []
for i in range(10):
observations.append(
Observation(9, {"test_key": i})
)
return observations
# Create two observable gauges using the defined generators.
gauge = meter.create_observable_gauge("gauge", [observable_gauge_generator])
gauge2 = meter.create_observable_gauge("gauge2", [observable_gauge_sequence])
# Wait for background execution.
input()
Dodawanie wyjątków niestandardowych
Wybrane biblioteki instrumentacji automatycznie zgłaszają wyjątki do usługi Application Insights.
Można jednak ręcznie zgłaszać wyjątki, które nie są raportowane przez biblioteki instrumentacji.
Na przykład wyjątki, które twój kod przechwytuje, nie są zwykle zgłaszane. Możesz zgłosić je, aby zwrócić uwagę na odpowiednie doświadczenia, w tym sekcję błędów i całościowe widoki transakcji.
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(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 aby zaktualizować status zakresu i rejestrować wyjątki.
Dodaj opentelemetry-api-1.0.0.jar (lub nowszą) do aplikacji:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Ustaw stan na error i zarejestruj wyjątek w kodzie:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
Ustaw stan na error i zarejestruj wyjątek w kodzie:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
Zestaw SDK Node.js eksportuje ręcznie zarejestrowane wyjątki związane z zakresem do usługi Application Insights jako wyjątki tylko wtedy, gdy są rejestrowane w głównym zakresie lub w podrzędnym zakresie zdalnym lub wewnętrznym.
export class CustomExceptionSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a span and record an exception
const tracer = trace.getTracer("testTracer");
const span = tracer.startSpan("hello");
try {
throw new Error("Test Error");
} catch (error) {
span.recordException(error as Error);
} finally {
span.end();
}
console.log("Exception recorded on span");
}
}
Zestaw SDK języka Python openTelemetry jest implementowany w taki sposób, że zgłoszone wyjątki są automatycznie przechwytywane i rejestrowane. Zobacz następujący 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 tę opcję wyłączyć w menedżerze kontekstu i użyć record_exception() 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)
...
Dodaj zakresy niestandardowe
Możesz dodać niestandardowy zakres w dwóch scenariuszach. Po pierwsze, gdy istnieje żądanie dotyczące zależności, które nie jest jeszcze zbierane przez bibliotekę instrumentacji. Po drugie, jeśli chcesz zaprezentować proces aplikacji jako przedział w pełnym widoku transakcji.
Uwaga
Klasy Activity i ActivitySource z przestrzeni nazw System.Diagnostics reprezentują pojęcia OpenTelemetry Span oraz Tracer. Można utworzyć ActivitySource bezpośrednio przy użyciu jego konstruktora zamiast przy użyciu TracerProvider. Każda ActivitySource klasa musi być jawnie połączona z TracerProvider przy użyciu 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 OpenTelemetry .NET Tracing.
// 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 usługę Application Insights dependencies.
ActivityKind.Server i ActivityKind.Consumer są mapowane na usługę Application Insights requests.
Uwaga
Klasy Activity i ActivitySource z przestrzeni nazw System.Diagnostics reprezentują pojęcia OpenTelemetry Span oraz Tracer. Można utworzyć ActivitySource bezpośrednio przy użyciu jego konstruktora zamiast przy użyciu TracerProvider. Każda ActivitySource klasa musi być jawnie połączona z TracerProvider przy użyciu 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 OpenTelemetry .NET Tracing.
// 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 usługę Application Insights dependencies.
ActivityKind.Server i ActivityKind.Consumer są mapowane na usługę Application Insights requests.
Używanie adnotacji OpenTelemetry
Najprostszym sposobem dodawania własnych zakresów jest użycie adnotacji OpenTelemetry @WithSpan .
Zakresy zasilają tabele requests i dependencies w usłudze Application Insights.
Dodaj opentelemetry-instrumentation-annotations-1.32.0.jar (lub nowszą) do aplikacji:
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-annotations</artifactId>
<version>1.32.0</version>
</dependency>
Użyj adnotacji @WithSpan, aby emitować zakres za każdym razem, gdy metoda jest wykonywana.
import io.opentelemetry.instrumentation.annotations.WithSpan;
@WithSpan(value = "your span name")
public void yourMethod() {
}
Domyślnie zakres kończy się w tabeli z typem zależności dependencies.
W przypadku metod reprezentujących zadania w tle, które nie są przechwytywane przez autoinstrumentację, zalecamy zastosowanie atrybutu kind = SpanKind.SERVER do adnotacji @WithSpan, aby upewnić się, że są one widoczne w tabeli Application Insights requests.
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:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
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();
}
Wstrzyknij OpenTelemetry
Utwórz element Tracer:
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = openTelemetry.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();
}
export class CustomTraceSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a custom span, add attributes/events, then end
const tracer = trace.getTracer("otel_azure_monitor_custom_trace_demo");
const span = tracer.startSpan("doWork");
try {
span.setAttribute("component", "worker");
span.setAttribute("operation.id", "42");
span.addEvent("invoking doWork");
for (let i = 0; i < 1_000_000; i++) { /* simulate work */ }
} catch (err) {
span.recordException(err as Error);
} finally {
span.end();
}
console.log("Custom span recorded");
}
}
Interfejs API OpenTelemetry może być używany do dodawania własnych spanów, które są wyświetlane w tabelach requests i dependencies w usłudze Application Insights.
Przykład kodu pokazuje, jak użyć metody tracer.start_as_current_span() do rozpoczęcia, ustawienia zakresu jako bieżący oraz zakończenia zakresu 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 InProc zależności.
Jeśli metoda reprezentuje zadanie w tle, które nie zostało jeszcze przechwycone przez funkcję automatycznej instrumentacji, zalecamy ustawienie atrybutu kind = SpanKind.SERVER, aby był wyświetlany w tabeli 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.
...
Wysyłanie zdarzeń niestandardowych
Usługa Application Insights przechowuje zdarzenia niestandardowe w customEvents tabeli. Jednym ze sposobów analizowania, filtrowania i wizualizowania ich jest użycie środowisk użycia usługi Application Insights.
Jeśli chcesz zautomatyzować zbieranie zdarzeń interakcji po stronie klienta, możesz użyć wtyczki w zestawie SDK języka JavaScript.
Zdarzenia niestandardowe są w publicznej wersji zapoznawczej i używają wersji Azure.Monitor.OpenTelemetry.AspNetCore 1.3.0-beta.3.
Aby wysłać CustomEvent przy użyciu ILogger, ustaw atrybut "microsoft.custom_event.name" w szablonie wiadomości.
// Create a logger factory and configure OpenTelemetry with Azure Monitor
var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter();
});
});
// Create a logger for the specified category
var logger = loggerFactory.CreateLogger(logCategoryName);
// Log a custom event with a custom name and additional attribute
// The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}", "test-event-name", "val1");
Zdarzenia niestandardowe są w publicznej wersji zapoznawczej i używają wersji Azure.Monitor.OpenTelemetry.Exporter 1.4.0-beta.3.
Aby wysłać CustomEvent przy użyciu ILogger, ustaw atrybut "microsoft.custom_event.name" w szablonie wiadomości.
// Create a logger factory and configure OpenTelemetry with Azure Monitor
var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter();
});
});
// Create a logger for the specified category
var logger = loggerFactory.CreateLogger(logCategoryName);
// Log a custom event with a custom name and additional attribute
// The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}", "test-event-name", "val1");
Aby wysłać customEvent przy użyciu Java agenta, ustaw atrybut "microsoft.custom_event.name" w rekordzie dziennika OpenTelemetry.
W zależności od tego, czy jest używany agent Java usługi Application Insights, czy automatyczna konfiguracja SDK, sposób pobierania rejestratora OpenTelemetry jest nieco inny. W poniższych przykładach opisano to szczegółowo.
Dla agenta Java usługi 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();
Automatyczna konfiguracja zestawu SDK:
import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigure;
import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigureOptions;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.logs.Logger;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder;
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorAutoConfigureOptions options = new AzureMonitorAutoConfigureOptions();
options.connectionString("<your connection string>");
AzureMonitorAutoConfigure.customize(sdkBuilder, options);
OpenTelemetry openTelemetry = sdkBuilder.build().getOpenTelemetrySdk();
Logger logger = openTelemetry.getLogsBridge().get("opentelemetry-logger");
logger.logRecordBuilder()
.setAttribute(AttributeKey.stringKey("microsoft.custom_event.name"),"test-event-name")
.setSeverity(Severity.INFO)
.emit();
Aby niezawodnie emitować zdarzenia niestandardowe, użyj bezpośrednio interfejsu API OpenTelemetry. Niektóre struktury rejestrowania nie obsługują dołączania ani analizowania atrybutu zdarzeń niestandardowych.
Nie można wysłać customEvent przy użyciu atrybutu "microsoft.custom_event.name" w natywnym środowisku Java.
Aby wysłać customEvent za pomocą logger.emit, ustaw atrybut "microsoft.custom_event.name" obiektu dziennika attributes. Inne atrybuty można również uwzględnić w razie potrzeby.
export class CustomEventSample {
static async run() {
// Dynamically import Azure Monitor and the OpenTelemetry logs API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { logs, SeverityNumber } = await import("@opentelemetry/api-logs");
// Initialize Azure Monitor (enables logs bridge)
const monitor = useAzureMonitor();
// Get a logger and emit a customEvent by setting the microsoft attribute key
const logger = logs.getLogger("my-app-logger");
logger.emit({
body: "Hello World!",
severityNumber: SeverityNumber.INFO,
attributes: {
"microsoft.custom_event.name": "test-event-name",
"additional_attrs": "val1",
},
});
// Example: populate client_IP via attribute 'client.address'
logger.emit({
body: "This entry will have a custom client_IP",
severityNumber: SeverityNumber.INFO,
attributes: {
"microsoft.custom_event.name": "test_event",
"client.address": "192.168.1.1",
},
});
console.log("Custom events emitted");
}
}
Aby wysłać element customEvent w języku Python, użyj biblioteki rejestrowania z atrybutem "microsoft.custom_event.name" w parametrze extra .
import logging
from azure.monitor.opentelemetry import configure_azure_monitor
# Set up your application logger
logger = logging.getLogger("my-app-logger")
# Configure Azure Monitor to collect logs from the specified logger name
configure_azure_monitor(
logger_name="my-app-logger", # Collect logs from your namespaced logger
)
# Log a custom event with a custom name and additional attribute
# The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.warning(
"Hello World!",
extra={
"microsoft.custom_event.name": "test-event-name",
"additional_attrs": "val1"
}
)
# You can also populate fields like client_IP with attribute `client.address`
logger.info(
"This entry will have a custom client_IP",
extra={
"microsoft.custom_event.name": "test_event",
"client.address": "192.168.1.1"
}
)
Modyfikowanie telemetrii
W tej sekcji opisano sposób modyfikowania danych telemetrycznych.
Dodawanie atrybutów rozpiętości
Te atrybuty mogą obejmować dodawanie właściwości niestandardowej do telemetrii. Atrybuty mogą również służyć do ustawiania pól opcjonalnych w schemacie usługi Application Insights, takich jak 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 wzbogacenia w bibliotece instrumentacji HttpClient zapewnia użytkownikom dostęp do HttpRequestMessage oraz 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:
Użyj niestandardowego procesora:
Napiwek
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 swojego projektu, używając następującego kodu:
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 wzbogacenia w bibliotece instrumentacji HttpClient zapewnia użytkownikom dostęp do samego komunikatu żądania HTTP. 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:
Użyj niestandardowego procesora:
Napiwek
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 swojego projektu, używając następującego kodu:
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 do dodawania atrybutów do spanów.
Dodanie co najmniej jednego atrybutu zakresu spowoduje wypełnienie pola customDimensions w tabeli requests, dependencies, traces lub exceptions.
Dodaj opentelemetry-api-1.0.0.jar (lub nowszą) do aplikacji:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Dodaj wymiary niestandardowe w swoim kodzie.
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
Dodaj wymiary niestandardowe w swoim kodzie.
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
export class SpanAttributeEnrichmentSample {
static async run() {
// Dynamically import the Azure Monitor integration
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
// Create a SpanEnrichingProcessor to add custom dimensions
class SpanEnrichingProcessor {
forceFlush() { return Promise.resolve(); }
shutdown() { return Promise.resolve(); }
onStart() {}
onEnd(span: any) {
(span as any).attributes = (span as any).attributes || {};
(span as any).attributes["CustomDimension1"] = "value1";
(span as any).attributes["CustomDimension2"] = "value2";
}
}
// Initialize Azure Monitor with the custom processor
const monitor = useAzureMonitor({
spanProcessors: [new SpanEnrichingProcessor()],
});
console.log("Span enrichment processor registered");
}
}
Użyj niestandardowego procesora:
...
# 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 swojego projektu, używając następującego kodu:
# 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 na rozpiętości. Usługa Application Insights używa adresu IP do generowania atrybutów lokalizacji użytkownika, a następnie domyślnie go odrzuca.
Użyj przykładu właściwości niestandardowej
// 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 właściwości niestandardowej
// 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>");
Język Java automatycznie wypełnia to pole.
To pole jest wypełniane automatycznie.
Użyj przykładu właściwości niestandardowej, ale zastąp te wiersze kodu:
export class SetUserIpSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor();
// Framework-agnostic helper to set client IP on the active server span
const setIpForRequest = (clientIp: string) => {
const span = trace.getActiveSpan();
if (span) {
// Preferred attribute for client IP
span.setAttribute("client.address", clientIp);
// Optional: legacy/alternate attribute
span.setAttribute("http.client_ip", clientIp);
}
};
// Call setIpForRequest("<IP Address>") from within your web framework's request pipeline
console.log("Use setIpForRequest('<IP Address>') inside your request handler to stamp the active span.");
}
}
Użyj przykładu właściwości niestandardowej
# 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 uwierzytelnionego 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.
Wypełnij pole w tabeli user ID, requests lub dependencies.
Dodaj opentelemetry-api-1.0.0.jar (lub nowszą) do aplikacji:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Ustaw user_Id w kodzie:
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser"); // (user_AuthenticatedId)
Span.current().setAttribute("enduser.pseudo.id", "myuser"); // (user_Id)
Wypełnij pole w tabeli user ID, requests lub dependencies.
Ustaw user_Id w kodzie:
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser"); // (user_AuthenticatedId)
Span.current().setAttribute("enduser.pseudo.id", "myuser"); // (user_Id)
Użyj przykładu właściwości niestandardowej, ale zastąp te wiersze kodu:
export class SetUserIdSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor();
// Framework-agnostic helper to set user identifiers on the active server span
const setUserForRequest = (authenticatedId?: string, anonymousId?: string) => {
const span = trace.getActiveSpan();
if (span) {
if (authenticatedId) span.setAttribute("enduser.id", authenticatedId); // user_AuthenticatedId
if (anonymousId) span.setAttribute("enduser.pseudo.id", anonymousId); // user_Id
}
};
// Call setUserForRequest("<authenticated-id>", "<anonymous-id>") inside your request handler
console.log("Use setUserForRequest('<auth-id>', '<anon-id>') inside your request handler to stamp the active span.");
}
}
Użyj przykładu właściwości niestandardowej, ale zastąp te wiersze kodu:
# Set the `enduser.id` attribute of the span to the specified user ID.
span._attributes["enduser.id"] = "<User ID>"
Dodawanie atrybutów dziennika
OpenTelemetry używa elementu .NET ILogger.
Dołączanie wymiarów niestandardowych do dzienników można wykonać przy użyciu szablonu komunikatu.
OpenTelemetry używa elementu .NET 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 instrumentowane. Dodawanie wymiarów niestandardowych do dzienników jest możliwe w następujący sposób:
W przypadku natywnych aplikacji Spring Boot, Logback jest gotowy do użycia.
export class BunyanLogAttributesSample {
static async run() {
// Dynamically import Azure Monitor and Bunyan
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const bunyanMod = await import("bunyan");
const bunyan = (bunyanMod as any).default ?? bunyanMod;
// Enable Azure Monitor integration and bunyan instrumentation
const monitor = useAzureMonitor({
instrumentationOptions: { bunyan: { enabled: true } },
});
// Emit a log with custom attributes
const log = (bunyan as any).createLogger({ name: "testApp" });
log.info({ key1: "value1", feature: "demo" }, "Warning log with properties");
console.log("Bunyan log with attributes emitted");
}
}
Biblioteka logowania języka Python jest autoinstrumentowana. Możesz dołączyć wymiary niestandardowe do swoich dzienników, przekazując słownik do argumentu extra.
...
# Create a warning log message with the properties "key1" and "value1".
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
Pobierz identyfikator śledzenia lub identyfikator zakresu
Aby uzyskać Trace ID i Span ID dla aktualnie aktywnego zakresu, wykonaj następujące kroki.
Uwaga
Klasy Activity i ActivitySource z przestrzeni nazw System.Diagnostics reprezentują pojęcia OpenTelemetry Span oraz Tracer. 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 OpenTelemetry .NET Tracing.
// 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 przestrzeni nazw System.Diagnostics reprezentują pojęcia OpenTelemetry Span oraz Tracer. 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 OpenTelemetry .NET Tracing.
// 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ć elementu opentelemetry-api, aby uzyskać ID trasowania lub ID zakresu.
Dodaj opentelemetry-api-1.0.0.jar (lub nowszą) do aplikacji:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Pobierz identyfikator śledzenia żądania i identyfikator zakresu w kodzie:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
Pobierz identyfikator śledzenia żądania i identyfikator zakresu w kodzie:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
Pobierz identyfikator śledzenia żądania i identyfikator zakresu w kodzie:
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);
}
}
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
Następne kroki
- Aby jeszcze bardziej skonfigurować dystrybucję OpenTelemetry, zobacz Azure Monitor OpenTelemetry configuration (Konfiguracja biblioteki OpenTelemetry w usłudze Azure Monitor).
- 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 umożliwić doświadczenia użytkowania, włącz monitorowanie użytkowników sieci Web lub przeglądarki.
- Aby zapoznać się z często zadawanymi pytaniami, krokami rozwiązywania problemów, opcjami pomocy technicznej lub przekazać opinię na temat funkcji OpenTelemetry, zobacz Pomoc, pomoc techniczna i opinie dotyczące usługi Azure Monitor Application Insights.
- Aby jeszcze bardziej skonfigurować dystrybucję OpenTelemetry, zobacz Azure Monitor OpenTelemetry configuration (Konfiguracja opentelemetrii usługi Azure Monitor)
- Aby przejrzeć kod źródłowy, zobacz repozytorium GitHub eksportera usługi Azure Monitor.
- Aby zainstalować pakiet NuGet, sprawdzić aktualizacje lub wyświetlić notatki dotyczące wydania, zobacz stronę Pakietu Azure Monitor Eksporter NuGet.
- 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 umożliwić doświadczenia użytkowania, włącz monitorowanie użytkowników sieci Web lub przeglądarki.
- Aby zapoznać się z często zadawanymi pytaniami, krokami rozwiązywania problemów, opcjami pomocy technicznej lub przekazać opinię na temat funkcji OpenTelemetry, zobacz Pomoc, pomoc techniczna i opinie dotyczące usługi Azure Monitor Application Insights.
- 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 wyświetlić informacje o wersji, zobacz informacje o wersji w usłudze GitHub.
- Aby zainstalować pakiet PyPI, sprawdzić aktualizacje lub wyświetlić informacje o wersji, odwiedź stronę Pakiet PyPI Dystro usługi Azure Monitor.
- Aby lepiej zapoznać się z usługami Azure Monitor Application Insights 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 Python.
- Aby wyświetlić dostępne instrumentacje i składniki OpenTelemetry, zobacz repozytorium OpenTelemetry Contributor Python na GitHubie.
- Aby umożliwić doświadczenia użytkowania, włącz monitorowanie użytkowników sieci Web lub przeglądarki.
- Aby zapoznać się z często zadawanymi pytaniami, krokami rozwiązywania problemów, opcjami pomocy technicznej lub przekazać opinię na temat funkcji OpenTelemetry, zobacz Pomoc, pomoc techniczna i opinie dotyczące usługi Azure Monitor Application Insights.