Az Azure Monitor-exportőr nem tartalmaz rendszerállapot-kódtárakat.
Az Azure SDK-k függőségeit az alábbi kódmintával gyűjtheti össze a forrásra való manuális feliratkozáshoz.
// 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();
Kérelmek
JMS-felhasználók
Kafka-felhasználók
Netty
Kvarc
RabbitMQ
Servlets
Tavaszi ütemezés
Feljegyzés
A Servlet és a Netty autoinstrumentációja magában foglalja a Java HTTP-szolgáltatások többségét, beleértve a Java EE, a Jakarta EE, a Spring Boot, a Quarkus és a Micronaut szolgáltatást.
Függőségek (plusz az alsóbb rétegbeli elosztott nyomkövetés propagálása)
Az Azure Monitor Application Insights-disztribúció részeként az alábbi OpenTelemetry Instrumentation-kódtárak szerepelnek. További információ: Azure SDK for JavaScript.
Példák a Python-naplózási kódtár használatára a GitHubon.
Az Azure SDKS által kibocsátott telemetriai adatok alapértelmezés szerint automatikusan összegyűjtve lesznek.
Lábjegyzetek
¹: Támogatja a nem kezelt/nem kezelt kivételek automatikus jelentését
²: Támogatja az OpenTelemetry-metrikákat
³: Alapértelmezés szerint a naplózás csak infoszinten vagy magasabb szinten történik. A beállítás módosításához tekintse meg a konfigurációs beállításokat.
⁴: Alapértelmezés szerint a naplózás csak akkor lesz összegyűjtve, ha a naplózás a FIGYELMEZTETÉS vagy magasabb szinten történik.
Feljegyzés
Az Azure Monitor OpenTelemetry Distros egyéni leképezést és logikát tartalmaz az Application Insights standard metrikák automatikus kibocsájtásához.
Tipp.
A rendszerállapot-kódtárakból automatikusan gyűjtött vagy az egyéni kódolásból manuálisan gyűjtött OpenTelemetry-metrikák jelenleg az Application Insights "egyéni mérőszámainak" számítanak számlázási célokra. További információ.
Közösségi rendszerállapot-kódtár hozzáadása
Az OpenTelemetry-közösség rendszerállapot-kódtárainak felvételekor automatikusan további adatokat gyűjthet.
Figyelemfelhívás
Nem támogatjuk és nem garantáljuk a közösségi eszközkódtárak minőségét. Javasoljuk, hogy egy a mi disztribúció, post vagy up-vote a mi visszajelzési közösség. Vegye figyelembe, hogy egyes adatok kísérleti OpenTelemetria-specifikációkon alapulnak, és jövőbeli kompatibilitástörő változásokat eredményezhetnek.
Közösségi kódtár hozzáadásához használja azokat vagy ConfigureOpenTelemetryMeterProviderConfigureOpenTelemetryTracerProvider metódusokat, miután hozzáadta a NuGet-csomagot a tárhoz.
// 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();
// 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();
A Java-disztribúciót nem terjesztheti ki közösségi rendszerállapot-kódtárakkal. Ha azt szeretné, hogy egy másik eszközkódtárat is szerepeltethessünk, nyisson meg egy hibát a GitHub-oldalunkon. A GitHub-lapra mutató hivatkozást a következő lépésekben találja.
A GraalVM Java natív alkalmazásokkal nem használhat közösségi rendszerállapot-kódtárakat.
Itt további OpenTelemetria-rendszerállapotok érhetők el, amelyeket a TraceHandler használatával lehet hozzáadni az ApplicationInsightsClientben:
// 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
});
Közösségi rendszerállapot-kódtár hozzáadásához (amely hivatalosan nem támogatott/szerepel az Azure Monitor disztribúcióban), közvetlenül a rendszerállapotokkal végezheti el a hangszerelést. A közösségi rendszerállapot-kódtárak listája itt található.
# 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())
Egyéni telemetriai adatok gyűjtése
Ez a szakasz bemutatja, hogyan gyűjthet egyéni telemetriát az alkalmazásból.
A nyelvtől és a jeltípustól függően különböző módokon gyűjthet egyéni telemetriát, például:
Az alábbi táblázat a jelenleg támogatott egyéni telemetriai típusokat jelöli:
Nyelv
Egyéni események
Egyéni metrikák
Függőségek
Kivételek
Lapmegtekintések
Kérelmek
Hívásláncok
ASP.NET Core
OpenTelemetry API
Igen
Igen
Igen
Igen
ILogger API
Igen
Klasszikus AI API
Java
OpenTelemetry API
Igen
Igen
Igen
Igen
Logback, Log4j, JUL
Igen
Igen
Mikrométeres metrikák
Igen
Klasszikus AI API
Igen
Igen
Igen
Igen
Igen
Igen
Igen
Node.js
OpenTelemetry API
Igen
Igen
Igen
Igen
Python
OpenTelemetry API
Igen
Igen
Igen
Igen
Python-naplózási modul
Igen
Eseménybővítmény
Igen
Igen
Feljegyzés
Az Application Insights Java 3.x figyeli a klasszikus Application Insights API-nak küldött telemetriát. Hasonlóképpen, az Application Insights Node.js 3.x gyűjti a klasszikus Application Insights API-val létrehozott eseményeket. Ez megkönnyíti a frissítést, és betölt egy rést az egyéni telemetriai támogatásban, amíg az OpenTelemetry API nem támogatja az összes egyéni telemetriai típust.
Egyéni metrikák hozzáadása
Ebben az összefüggésben az egyéni metrikák kifejezés a kód manuális rendszerezésére vonatkozik, hogy további metrikákat gyűjtsön az OpenTelemetry Instrumentation Libraries automatikusan gyűjtött adatain túl.
Az OpenTelemetry API hat metrika "eszközt" kínál a különböző metrikaforgatókönyvek lefedéséhez, és a metrikák vizualizációja során a megfelelő "Aggregációs típust" kell választania. Ez a követelmény akkor érvényes, ha az OpenTelemetry Metric API használatával metrikákat küld, és rendszerállapot-kódtárat használ.
A táblázatban láthatónál több aggregációtípus általában nem értelmezhető.
Az OpenTelemetria specifikációja ismerteti az eszközöket, és példákat tartalmaz arra, hogy mikor használhatja az egyes eszközöket.
Tipp.
A hisztogram a legsokoldalúbb és legszorosabb egyenértékű az Application Insights GetMetric classic API-val. Az Azure Monitor jelenleg az öt támogatott összesítési típusba simítja a hisztogram-eszközt, és a percentilisek támogatása folyamatban van. Bár kevésbé sokoldalú, más OpenTelemetry-eszközök kevésbé befolyásolják az alkalmazás teljesítményét.
Az alkalmazásindításnak elő kell fizetnie egy meter név szerint:
// 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();
Ezt Meter a nevet kell inicializálni:
// 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 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);
// 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
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()
Az alkalmazásindításnak elő kell fizetnie egy meter név szerint:
// 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();
Ezt Meter a nevet kell inicializálni:
// 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
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()
Az alkalmazásindításnak elő kell fizetnie egy meter név szerint:
// 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();
Ezt Meter a nevet kell inicializálni:
// 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
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()
Egyéni kivételek hozzáadása
A rendszerállapot-kódtárak kiválasztása automatikusan jelenti az Application Insights kivételeit.
Előfordulhat azonban, hogy manuálisan szeretné jelenteni a kivételeket a rendszerállapot-kódtárak jelentéseien túl.
A kód által észlelt kivételeket például általában nem jelenti a rendszer. Előfordulhat, hogy fel szeretné őket jelenteni, hogy felhívják a figyelmet a releváns élményekre, beleértve a hibák szakaszt és a végpontok közötti tranzakciónézeteket.
// 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);
}
}
Kivétel naplózása a következővel 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" });
}
Kivétel naplózása tevékenység használatával:
// 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);
}
}
Kivétel naplózása a következővel 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" });
}
A span és a record kivételek állapotának frissítésére használható opentelemetry-api .
Adja hozzá opentelemetry-api-1.0.0.jar (vagy újabb) az alkalmazáshoz:
A Node.js SDK csak akkor exportálja ezeket a manuálisan rögzített span-alapú kivételeket az Application Insightsba kivételként, ha távoli, belső hatókörű gyermekeken rögzítik őket, vagy ha a kivételt felső szintű hatókörben rögzítik.
// 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);
}
Az OpenTelemetria Python SDK úgy van implementálva, hogy a rendszer automatikusan rögzítse és rögzítse a kidobott kivételeket. Erre a viselkedésre a következő kódmintában talál példát:
# 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")
Ha manuálisan szeretné rögzíteni a kivételeket, letilthatja ezt a beállítást a környezetkezelőben, és közvetlenül használhatja record_exception() a következő példában látható módon:
...
# 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)
...
Egyéni spanok hozzáadása
Előfordulhat, hogy két forgatókönyvben szeretne egyéni tartományt hozzáadni. Először is, ha van egy olyan függőségi kérés, amelyet még nem gyűjtött össze egy eszközkódtár. Másodszor, ha egy alkalmazásfolyamatot szeretne modellezni a teljes körű tranzakciós nézetben.
A Activity névtérből származó System.Diagnostics osztályok és ActivitySource osztályok az OpenTelemetry fogalmaitSpan, illetve Tracerazokat jelölik. Közvetlenül a konstruktor használatával hozhat létre ActivitySource , nem pedig a használatával TracerProvider. Minden ActivitySource osztályhoz explicit módon kell kapcsolódni TracerProvider a használatával AddSource(). Ennek az az oka, hogy az OpenTelemetry tracing API egyes részei közvetlenül a .NET-futtatókörnyezetbe vannak beépítve. További információ: Bevezetés az OpenTelemetry .NET Tracing API használatába.
// 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 alapértelmezett érték, ActivityKind.Internalde bármely más ActivityKindelemet megadhat.
ActivityKind.Client, ActivityKind.Producerés ActivityKind.Internal az Application Insightsra dependenciesvan leképezve.
ActivityKind.Server és ActivityKind.Consumer az Application Insightsra requestsvan leképezve.
Feljegyzés
A Activity névtérből származó System.Diagnostics osztályok és ActivitySource osztályok az OpenTelemetry fogalmaitSpan, illetve Tracerazokat jelölik. Közvetlenül a konstruktor használatával hozhat létre ActivitySource , nem pedig a használatával TracerProvider. Minden ActivitySource osztályhoz explicit módon kell kapcsolódni TracerProvider a használatával AddSource(). Ennek az az oka, hogy az OpenTelemetry tracing API egyes részei közvetlenül a .NET-futtatókörnyezetbe vannak beépítve. További információ: Bevezetés az OpenTelemetry .NET Tracing API használatába.
// 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 alapértelmezett érték, ActivityKind.Internalde bármely más ActivityKindelemet megadhat.
ActivityKind.Client, ActivityKind.Producerés ActivityKind.Internal az Application Insightsra dependenciesvan leképezve.
ActivityKind.Server és ActivityKind.Consumer az Application Insightsra requestsvan leképezve.
Az OpenTelemetry-széljegyzet használata
A legegyszerűbben az OpenTelemetry @WithSpan jegyzeteinek használatával adhat hozzá saját tartományokat.
A spanok feltöltik a táblákat és dependencies a requests táblákat az Application Insightsban.
Adja hozzá opentelemetry-instrumentation-annotations-1.32.0.jar (vagy újabb) az alkalmazáshoz:
A span alapértelmezés szerint függőségtípusú dependenciesInProctáblába kerül.
Az automatikusan nem rögzített háttérfeladatot képviselő metódusok esetében javasoljuk, hogy alkalmazza az attribútumot kind = SpanKind.SERVER a @WithSpan széljegyzetre, hogy azok megjelenjenek az Application Insights requests táblában.
Az OpenTelemetry API használata
Ha a fenti OpenTelemetria-széljegyzet @WithSpan nem felel meg az igényeinek, az OpenTelemetry API-val hozzáadhatja a spanokat.
Adja hozzá opentelemetry-api-1.0.0.jar (vagy újabb) az alkalmazáshoz:
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = openTelemetry.getTracer("com.example");
Hozzon létre egy spant, állítsa aktuálissá, majd fejezd be:
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();
Az OpenTelemetry API-val saját tartományokat adhat hozzá, amelyek az Application Insightsban és dependencies a requests táblákban jelennek meg.
A példakód bemutatja, hogyan indíthatja el a tracer.start_as_current_span() metódust, hogyan teheti aktuálissá a pántot, és hogyan fejezheti be a spant a környezetében.
...
# 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)
...
Alapértelmezés szerint a span a dependencies táblában van, amelynek függőségtípusa a következő InProc: .
Ha a metódus olyan háttérfeladatot jelöl, amelyet még nem rögzített automatikusan, javasoljuk, hogy állítsa be az attribútumot kind = SpanKind.SERVER , hogy az megjelenjen az Application Insights requests táblában.
...
# 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.
...
Egyéni telemetriai adatok küldése a Klasszikus Application Insights API használatával
Javasoljuk, hogy amikor csak lehetséges, használja az OpenTelemetry API-kat, de előfordulhatnak forgatókönyvek, amikor a klasszikus Application Insights API-t kell használnia.
Egyéni telemetriai adatok nem küldhetőek a Java natív Application Insights klasszikus API-jával.
Ha egyéni eseményeket szeretne hozzáadni, vagy hozzá szeretne férni az Application Insights API-hoz, cserélje le a @azure/monitor-opentelemetry csomagot a applicationinsightsv3 bétacsomagra. Ugyanazokat a metódusokat és interfészeket kínálja, és az összes mintakódot a v3 bétacsomagra @azure/monitor-opentelemetry alkalmazza.
// Import the TelemetryClient class from the Application Insights SDK for JavaScript.
const { TelemetryClient } = require("applicationinsights");
// Create a new TelemetryClient instance.
const telemetryClient = new TelemetryClient();
Ezután az egyéni telemetriai adatok küldéséhez használja a TelemetryClient következőt:
Események
// Create an event telemetry object.
let eventTelemetry = {
name: "testEvent"
};
// Send the event telemetry object to Azure Monitor Application Insights.
telemetryClient.trackEvent(eventTelemetry);
Naplók
// Create a trace telemetry object.
let traceTelemetry = {
message: "testMessage",
severity: "Information"
};
// Send the trace telemetry object to Azure Monitor Application Insights.
telemetryClient.trackTrace(traceTelemetry);
Kivételek
// 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);
}
Más nyelvektől eltérően a Python nem rendelkezik Application Insights SDK-val. Az Azure Monitor OpenTelemetry Disztribúcióval minden monitorozási igényét kielégítheti, kivéve a küldést customEvents. Amíg az OpenTelemetry Events API nem stabilizálódik, az Azure Monitor Eseménybővítmény és az Azure Monitor OpenTelemetria disztribúció használatával küldje el customEvents az Application Insightsnak.
Használja a track_event bővítményben kínált API-t a customEvents küldéséhez:
...
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()
...
Telemetria módosítása
Ez a szakasz bemutatja, hogyan módosíthatja a telemetriát.
Span attribútumok hozzáadása
Ezek az attribútumok közé tartozhat egy egyéni tulajdonság hozzáadása a telemetriához. Attribútumokkal is beállíthat választható mezőket az Application Insights-sémában, például az ügyfél IP-címében.
Egyéni tulajdonság hozzáadása spanhoz
A spanokhoz hozzáadott attribútumok egyéni tulajdonságokként lesznek exportálva. Feltöltik a customDimensions mezőt a kérések, függőségek, nyomkövetések vagy kivételek táblában.
A rendszerállapot-kódtárak által biztosított lehetőségek használatának előnye, hogy ha elérhetők, a teljes környezet elérhető. Ennek eredményeképpen a felhasználók további attribútumokat adhatnak hozzá vagy szűrhetnek. A HttpClient-eszköztár bővítési lehetősége például hozzáférést biztosít a felhasználóknak a HttpRequestMessage-hez és magához a HttpResponseMessage-hez . Bármit kiválaszthatnak belőle, és attribútumként tárolhatják.
Számos rendszerállapot-kódtár kínál bővítési lehetőséget. Útmutatásért tekintse meg az egyes eszközkódtárak olvasási fájljait:
Az Azure Monitor hozzáadása előtt adja hozzá az itt látható processzort.
// 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();
Adja hozzá ActivityEnrichingProcessor.cs a projekthez a következő kóddal:
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");
}
}
Span attribútumok hozzáadásához használja az alábbi két módszer egyikét:
Használja a rendszerállapot-kódtárak által biztosított beállításokat.
Adjon hozzá egy egyéni span processzort.
Tipp.
A rendszerállapot-kódtárak által biztosított lehetőségek használatának előnye, hogy ha elérhetők, a teljes környezet elérhető. Ennek eredményeképpen a felhasználók további attribútumokat adhatnak hozzá vagy szűrhetnek. A HttpClient-rendszerállapot-kódtár bővítési lehetősége például hozzáférést biztosít a felhasználóknak magához a httpRequestMessage-hez. Bármit kiválaszthatnak belőle, és attribútumként tárolhatják.
Számos rendszerállapot-kódtár kínál bővítési lehetőséget. Útmutatásért tekintse meg az egyes eszközkódtárak olvasási fájljait:
Adja hozzá az itt látható processzort az Azure Monitor-exportőr előtt .
// 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();
Adja hozzá ActivityEnrichingProcessor.cs a projekthez a következő kóddal:
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");
}
}
A spanok attribútumainak hozzáadására is használható opentelemetry-api .
Egy vagy több span attribútum hozzáadása feltölti a customDimensions mezőt a requests, dependencies, traces, vagy exceptions táblában.
Adja hozzá opentelemetry-api-1.0.0.jar (vagy újabb) az alkalmazáshoz:
...
# 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],
)
...
Adja hozzá SpanEnrichingProcessor a projekthez a következő kóddal:
# 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"
A felhasználói IP-cím beállítása
A kérések client_IP mezőjét feltöltheti egy attribútum beállításával. Az Application Insights az IP-cím használatával hoz létre felhasználói helyattribútumokat, majd alapértelmezés szerint elveti.
Használja az egyéni tulajdonság példáját, de cserélje le a következő kódsorokat a következőben 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>");
Használja az egyéni tulajdonság példáját, de cserélje le a következő kódsorokat a következőben 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>");
...
// 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>";
}
}
Használja az egyéni tulajdonság példáját, de cserélje le a következő kódsorokat a következőben SpanEnrichingProcessor.py:
# Set the `http.client_ip` attribute of the span to the specified IP address.
span._attributes["http.client_ip"] = "<IP Address>"
A felhasználói azonosító vagy a hitelesített felhasználói azonosító beállítása
A kérések user_Id vagy user_AuthenticatedId mezőjét az alábbi útmutató segítségével töltheti fel. A felhasználói azonosító névtelen felhasználói azonosító. A hitelesített felhasználói azonosító egy ismert felhasználói azonosító.
Fontos
A hitelesített felhasználói azonosító beállítása előtt tekintse meg a vonatkozó adatvédelmi jogszabályokat.
...
// 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>";
}
}
Az OpenTelemetry a . NET's ILogger.
Az egyéni dimenziók naplókhoz való csatolása üzenetsablon használatával végezhető el.
Az OpenTelemetry a . NET's ILogger.
Az egyéni dimenziók naplókhoz való csatolása üzenetsablon használatával végezhető el.
A rendszer automatikusan beszúrja a kijelentkezést, a Log4j-t és a java.util.naplózást. Az egyéni dimenziók naplókhoz való csatolása az alábbi módokon végezhető el:
Log4j 2.0 MapMessage (a MapMessage rendszer naplóüzenetként rögzíti a kulcsát "message" )
A Python naplózási kódtára automatikusan be van iktatásra. Egyéni dimenziókat a naplókhoz úgy csatolhat, ha egy szótárt ad át a extra naplók argumentumába:
...
# Create a warning log message with the properties "key1" and "value1".
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
A nyomkövetési azonosító vagy a span azonosítójának lekérése
A jelenleg aktív span és Span ID az aktuális span az alábbi lépések végrehajtásával szerezhető beTrace ID.
A Activity névtérből származó System.Diagnostics osztályok és ActivitySource osztályok az OpenTelemetry fogalmaitSpan, illetve Tracerazokat jelölik. Ennek az az oka, hogy az OpenTelemetry tracing API egyes részei közvetlenül a .NET-futtatókörnyezetbe vannak beépítve. További információ: Bevezetés az OpenTelemetry .NET Tracing API használatába.
// 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();
Feljegyzés
A Activity névtérből származó System.Diagnostics osztályok és ActivitySource osztályok az OpenTelemetry fogalmaitSpan, illetve Tracerazokat jelölik. Ennek az az oka, hogy az OpenTelemetry tracing API egyes részei közvetlenül a .NET-futtatókörnyezetbe vannak beépítve. További információ: Bevezetés az OpenTelemetry .NET Tracing API használatába.
// 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();
A nyomkövetési azonosítót vagy a span azonosítót is lekérheti opentelemetry-api .
Adja hozzá opentelemetry-api-1.0.0.jar (vagy újabb) az alkalmazáshoz:
Kérje le a kérelem nyomkövetési azonosítóját és a span id azonosítót a kódban:
// 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;
Kérje le a kérelem nyomkövetési azonosítóját és a span id azonosítót a kódban:
# 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
A NuGet-csomag telepítéséhez, frissítések kereséséhez vagy kibocsátási megjegyzések megtekintéséhez tekintse meg az Azure Monitor AspNetCore NuGet-csomag oldalát.
A NuGet-csomag telepítéséhez, a frissítések kereséséhez vagy a kibocsátási megjegyzések megtekintéséhez tekintse meg az Azure Monitor Exportőr NuGet-csomag oldalát.
A PyPI-csomag telepítéséhez, a frissítések kereséséhez vagy a kibocsátási megjegyzések megtekintéséhez tekintse meg az Azure Monitor Distro PyPI-csomag oldalát.
Az Azure Monitor Application Insights és az OpenTelemetria megismeréséhez tekintse meg az Azure Monitor példaalkalmazást.