Menambahkan, memodifikasi, dan memfilter OpenTelemetry
Artikel
Artikel ini menyediakan panduan tentang cara menambahkan, memodifikasi, dan memfilter OpenTelemetry untuk aplikasi menggunakan Azure Monitor Application Insights.
Pengekspor Azure Monitor tidak menyertakan pustaka instrumentasi apa pun.
Anda dapat mengumpulkan dependensi dari Azure SDK menggunakan sampel kode berikut untuk berlangganan sumber secara manual.
// 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();
Permintaan
Konsumen JMS
Konsumen Kafka
Netty
Quartz
RabbitMQ
Servlet
Penjadwalan Spring
Catatan
Autoinstrumentasi Servlet dan Netty mencakup sebagian besar layanan HTTP Java, termasuk Java EE, Jakarta EE, Spring Boot, Quarkus, dan Micronaut.
Untuk aplikasi asli Quartz, lihat dokumentasi Quarkus.
Pustaka Instrumentasi OpenTelemetry berikut disertakan sebagai bagian dari Distro Application Insights Azure Monitor. Untuk informasi selengkapnya, lihat Azure SDK untuk JavaScript.
Contoh penggunaan pustaka pengelogan Python dapat ditemukan di GitHub.
Telemetri yang dipancarkan oleh Azure SDKS dikumpulkan secara otomatis secara default.
Catatan kaki
¹: Mendukung pelaporan otomatis pengecualian yang tidak tertangani/tidak tertangani
²: Mendukung Metrik OpenTelemetry
³: Secara default, pengelogan hanya dikumpulkan pada tingkat INFO atau yang lebih tinggi. Untuk mengubah pengaturan ini, lihat opsi konfigurasi.
⁴: Secara default, pengelogan hanya dikumpulkan ketika pengelogan tersebut dilakukan pada tingkat PERINGATAN atau yang lebih tinggi.
Catatan
Distro OpenTelemetry Azure Monitor mencakup pemetaan dan logika kustom untuk memancarkan metrik standar Application Insights secara otomatis.
Tip
Semua metrik OpenTelemetry baik yang dikumpulkan secara otomatis dari pustaka instrumentasi atau dikumpulkan secara manual dari pengodean kustom saat ini dianggap sebagai "metrik kustom" Application Insights untuk tujuan penagihan. Pelajari selengkapnya.
Menambahkan pustaka instrumentasi komunitas
Anda dapat mengumpulkan lebih banyak data secara otomatis saat menyertakan pustaka instrumentasi dari komunitas OpenTelemetry.
Perhatian
Kami tidak mendukung atau menjamin kualitas pustaka instrumentasi komunitas. Untuk menyarankan satu untuk distro, posting, atau up-vote kami di komunitas umpan balik kami. Perlu diketahui, beberapa didasarkan pada spesifikasi OpenTelemetry eksperimental dan mungkin memperkenalkan perubahan yang melanggar di masa depan.
Untuk menambahkan pustaka komunitas, gunakan ConfigureOpenTelemetryMeterProvider metode atau ConfigureOpenTelemetryTracerProvider , setelah menambahkan paket NuGet untuk pustaka.
Contoh berikut menunjukkan bagaimana Instrumentasi Runtime dapat ditambahkan untuk mengumpulkan metrik tambahan:
// 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();
Contoh berikut menunjukkan bagaimana Instrumentasi Runtime dapat ditambahkan untuk mengumpulkan metrik tambahan:
// 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();
Anda tidak dapat memperluas Java Distro dengan pustaka instrumentasi komunitas. Untuk meminta agar kami menyertakan pustaka instrumentasi lain, buka masalah di halaman GitHub kami. Anda dapat menemukan tautan ke halaman GitHub kami di Langkah Berikutnya.
Anda tidak dapat menggunakan pustaka instrumentasi komunitas dengan aplikasi asli GraalVM Java.
Instrumentasi OpenTelemetry lainnya tersedia di sini dan dapat ditambahkan menggunakan TraceHandler di ApplicationInsightsClient:
// 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
});
Untuk menambahkan pustaka instrumentasi komunitas (tidak didukung/disertakan secara resmi dalam distro Azure Monitor), Anda dapat melengkapi instrumen langsung dengan instrumentasi. Daftar pustaka instrumentasi komunitas dapat ditemukan di sini.
# 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())
Mengumpulkan telemetri kustom
Bagian ini menjelaskan cara mengumpulkan telemetri kustom dari aplikasi Anda.
Bergantung pada bahasa dan jenis sinyal Anda, ada berbagai cara untuk mengumpulkan telemetri kustom, termasuk:
OpenTelemetry API
Pustaka pengelogan/metrik khusus bahasa
API Klasik Application Insights
Tabel berikut ini mewakili jenis telemetri kustom yang saat ini didukung:
Bahasa
Peristiwa Kustom
Metrik Kustom
Dependensi
Pengecualian
Tampilan Halaman
Permintaan
Jejak
Inti ASP.NET
OpenTelemetry API
Ya
Ya
Ya
Ya
ILogger API
Ya
API Klasik AI
Java
OpenTelemetry API
Ya
Ya
Ya
Ya
Logback, Log4j, JUL
Ya
Ya
Metrik Mikrometer
Ya
API Klasik AI
Ya
Ya
Ya
Ya
Ya
Ya
Ya
Node.js
OpenTelemetry API
Ya
Ya
Ya
Ya
Python
OpenTelemetry API
Ya
Ya
Ya
Ya
Modul Pengelogan Python
Ya
Ekstensi Peristiwa
Ya
Ya
Catatan
Application Insights Java 3.x mendengarkan telemetri yang dikirim ke API Application Insights Classic. Demikian pula, Application Insights Node.js 3.x mengumpulkan peristiwa yang dibuat dengan API Klasik Application Insights. Ini membuat peningkatan lebih mudah dan mengisi kesenjangan dalam dukungan telemetri kustom kami sampai semua jenis telemetri kustom didukung melalui API OpenTelemetry.
Menambahkan metrik kustom
Dalam konteks ini, istilah metrik kustom mengacu pada instrumen kode Anda secara manual untuk mengumpulkan metrik tambahan di luar apa yang dikumpulkan pustaka Instrumentasi OpenTelemetry secara otomatis.
API OpenTelemetry menawarkan enam metrik "instrumen" untuk mencakup berbagai skenario metrik dan Anda perlu memilih "Jenis Agregasi" yang benar saat memvisualisasikan metrik di Metrics Explorer. Persyaratan ini berlaku saat menggunakan API Metrik OpenTelemetry untuk mengirim metrik dan saat menggunakan pustaka instrumentasi.
Jenis agregasi di luar apa yang ditunjukkan dalam tabel biasanya tidak bermakna.
Spesifikasi OpenTelemetry menjelaskan instrumen dan memberikan contoh kapan Anda dapat menggunakan masing-masing instrumen.
Tip
Histogram adalah yang paling serbaguna dan paling setara dengan API Application Insights GetMetric Classic. Azure Monitor saat ini meratakan instrumen histogram ke dalam lima jenis agregasi yang didukung, dan dukungan untuk persentil sedang berlangsung. Meskipun kurang serbaguna, instrumen OpenTelemetry lainnya memiliki dampak yang lebih rendah pada performa aplikasi Anda.
Startup aplikasi harus berlangganan Meter menurut nama:
// 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();
Meter harus diinisialisasi menggunakan nama yang sama:
// 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()
Startup aplikasi harus berlangganan Meter menurut nama:
// 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();
Meter harus diinisialisasi menggunakan nama yang sama:
// 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()
Startup aplikasi harus berlangganan Meter menurut nama:
// 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();
Meter harus diinisialisasi menggunakan nama yang sama:
// 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()
Menambahkan pengecualian kustom
Pilih pustaka instrumentasi secara otomatis melaporkan pengecualian ke Application Insights.
Namun, Anda mungkin ingin melaporkan pengecualian secara manual di luar laporan pustaka instrumentasi.
Misalnya, pengecualian yang ditangkap oleh kode Anda biasanya tidak dilaporkan. Anda mungkin ingin melaporkannya untuk menarik perhatian dalam pengalaman yang relevan termasuk bagian kegagalan dan tampilan transaksi end-to-end.
Untuk mencatat Pengecualian menggunakan Aktivitas:
// 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);
}
}
Untuk mencatat Pengecualian menggunakan 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" });
}
Untuk mencatat Pengecualian menggunakan Aktivitas:
// 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);
}
}
Untuk mencatat Pengecualian menggunakan 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" });
}
Anda dapat menggunakan opentelemetry-api untuk memperbarui status rentang dan pengecualian rekaman.
Tambahkan opentelemetry-api-1.0.0.jar (atau yang lebih baru) ke aplikasi Anda:
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { trace, SpanKind } = 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", {
kind: SpanKind.SERVER
});
// 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);
}
OpenTelemetry Python SDK diimplementasikan sedemikian sehingga pengecualian yang dilemparkan secara otomatis ditangkap dan direkam. Lihat sampel kode berikut untuk contoh perilaku ini:
# 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")
Jika Anda ingin merekam pengecualian secara manual, Anda dapat menonaktifkan opsi tersebut dalam manajer konteks dan menggunakan record_exception() langsung seperti yang ditunjukkan dalam contoh berikut:
...
# 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)
...
Menambahkan rentang kustom
Anda mungkin ingin menambahkan rentang kustom dalam dua skenario. Pertama, ketika ada permintaan dependensi yang belum dikumpulkan oleh pustaka instrumentasi. Kedua, ketika Anda ingin memodelkan proses aplikasi sebagai rentang pada tampilan transaksi end-to-end.
Kelas Activity dan ActivitySource dari namespace layanan System.Diagnostics, masing-masing mewakili konsep OpenTelemetry dari Span dan Tracer. Anda membuat ActivitySource secara langsung dengan menggunakan konstruktornya daripada menggunakan TracerProvider. Setiap ActivitySource kelas harus tersambung secara eksplisit TracerProvider dengan menggunakan AddSource(). Hal itu karena bagian dari OpenTelemetry yang melacak API dimasukkan secara langsung ke dalam runtime bahasa umum .NET. Untuk mempelajari selengkapnya, lihat Pengenalan API Pelacakan OpenTelemetry .NET.
// 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 default ke ActivityKind.Internal, tetapi Anda dapat menyediakan yang lain ActivityKind.
ActivityKind.Client, ActivityKind.Producer, dan ActivityKind.Internal dipetakan ke Application Insights dependencies.
ActivityKind.Server dan ActivityKind.Consumer dipetakan ke Application Insights requests.
Catatan
Kelas Activity dan ActivitySource dari namespace layanan System.Diagnostics, masing-masing mewakili konsep OpenTelemetry dari Span dan Tracer. Anda membuat ActivitySource secara langsung dengan menggunakan konstruktornya daripada menggunakan TracerProvider. Setiap ActivitySource kelas harus tersambung secara eksplisit TracerProvider dengan menggunakan AddSource(). Hal itu karena bagian dari OpenTelemetry yang melacak API dimasukkan secara langsung ke dalam runtime bahasa umum .NET. Untuk mempelajari selengkapnya, lihat Pengenalan API Pelacakan OpenTelemetry .NET.
// 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 default ke ActivityKind.Internal, tetapi Anda dapat menyediakan yang lain ActivityKind.
ActivityKind.Client, ActivityKind.Producer, dan ActivityKind.Internal dipetakan ke Application Insights dependencies.
ActivityKind.Server dan ActivityKind.Consumer dipetakan ke Application Insights requests.
Menggunakan anotasi OpenTelemetry
Cara paling sederhana untuk menambahkan rentang Anda sendiri adalah dengan menggunakan anotasi OpenTelemetry @WithSpan .
Rentang mengisi tabel requests dan dependencies di Application Insights.
Tambahkan opentelemetry-instrumentation-annotations-1.32.0.jar (atau yang lebih baru) ke aplikasi Anda:
Secara default, rentang berakhir dalam dependencies tabel dengan jenis InProcdependensi .
Untuk metode yang mewakili pekerjaan latar belakang yang tidak diambil oleh autoinstrumentasi, sebaiknya terapkan atribut kind = SpanKind.SERVER ke @WithSpan anotasi untuk memastikannya muncul di tabel Application Insights requests .
Menggunakan API OpenTelemetry
Jika anotasi OpenTelemetry @WithSpan sebelumnya tidak memenuhi kebutuhan Anda, Anda dapat menambahkan rentang Anda dengan menggunakan API OpenTelemetry.
Tambahkan opentelemetry-api-1.0.0.jar (atau yang lebih baru) ke aplikasi Anda:
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = openTelemetry.getTracer("com.example");
Buat rentang, buat saat ini, lalu akhiri:
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();
API OpenTelemetry dapat digunakan untuk menambahkan rentang Anda sendiri, yang muncul dalam requests tabel dan dependencies di Application Insights.
Contoh kode menunjukkan cara menggunakan tracer.start_as_current_span() metode untuk memulai, membuat rentang saat ini, dan mengakhiri rentang dalam konteksnya.
...
# 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)
...
Secara default, rentang berada dalam dependencies tabel dengan jenis dependensi .InProc
Jika metode Anda mewakili pekerjaan latar belakang yang belum diambil oleh autoinstrumentation, sebaiknya atur atribut kind = SpanKind.SERVER untuk memastikannya muncul di tabel 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.
...
Mengirim telemetri kustom menggunakan API Klasik Application Insights
Sebaiknya gunakan API OpenTelemetry jika memungkinkan, tetapi mungkin ada beberapa skenario saat Anda harus menggunakan API Klasik Application Insights.
Tidak dimungkinkan untuk mengirim telemetri kustom menggunakan API Klasik Application Insights di Java asli.
Jika Anda ingin menambahkan peristiwa kustom atau mengakses API Application Insights, ganti @azure/monitor-opentelemetry paket dengan applicationinsightspaket Beta v3. Ini menawarkan metode dan antarmuka yang sama, dan semua kode sampel untuk @azure/monitor-opentelemetry berlaku untuk paket Beta v3.
// Import the TelemetryClient class from the Application Insights SDK for JavaScript.
const { TelemetryClient } = require("applicationinsights");
// Create a new TelemetryClient instance.
const telemetryClient = new TelemetryClient();
Kemudian gunakan TelemetryClient untuk mengirim telemetri kustom:
Peristiwa
// Create an event telemetry object.
let eventTelemetry = {
name: "testEvent"
};
// Send the event telemetry object to Azure Monitor Application Insights.
telemetryClient.trackEvent(eventTelemetry);
Log
// Create a trace telemetry object.
let traceTelemetry = {
message: "testMessage",
severity: "Information"
};
// Send the trace telemetry object to Azure Monitor Application Insights.
telemetryClient.trackTrace(traceTelemetry);
Pengecualian
// 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);
}
Tidak seperti bahasa lain, Python tidak memiliki Application Insights SDK. Anda dapat memenuhi semua kebutuhan pemantauan Anda dengan Distro OpenTelemetry Azure Monitor, kecuali untuk mengirim customEvents. Hingga API Peristiwa OpenTelemetry stabil, gunakan Ekstensi Peristiwa Azure Monitor dengan Distro OpenTelemetry Azure Monitor untuk mengirim customEvents ke Application Insights.
Gunakan API yang track_event ditawarkan dalam ekstensi untuk mengirim customEvents:
...
from azure.monitor.events.extension import track_event
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor()
# Use the track_event() api to send custom event telemetry
# Takes event name and custom dimensions
track_event("Test event", {"key1": "value1", "key2": "value2"})
input()
...
Mengubah telemetri
Bagian ini menjelaskan cara memodifikasi telemetri.
Menambahkan atribut rentang
Atribut ini mungkin menambahkan properti kustom ke telemetri Anda. Anda mungkin juga menggunakan atribut untuk mengatur bidang opsional dalam Skema Application Insights seperti IP Klien.
Menambahkan properti kustom ke Rentang
Atribut apa pun yang Anda tambahkan kepada rentang diekspor sebagai properti kustom. Mereka mengisi bidang customDimensions dalam tabel permintaan, dependensi, jejak, atau pengecualian.
Keuntungan menggunakan opsi yang disediakan oleh pustaka instrumentasi, ketika opsi tersebut ada, yaitu tersedianya seluruh konteks. Sebagai hasilnya, pengguna dapat memilih untuk menambahkan atau memfilter lebih banyak atribut. Misalnya, opsi pengayaan di pustaka instrumentasi HttpClient memberi pengguna akses ke HttpRequestMessage dan HttpResponseMessage itu sendiri. Mereka dapat memilih apa pun darinya dan menyimpannya sebagai atribut.
Banyak perpustakaan instrumentasi memberikan opsi yang dapat memperkaya. Sebagai panduan, lihat file readme dari pustaka instrumentasi individual:
Tambahkan prosesor yang ditampilkan di sini sebelum menambahkan 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();
Tambahkan ActivityEnrichingProcessor.cs kode berikut ke proyek Anda:
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");
}
}
Untuk menambahkan atribut rentang, gunakan salah satu dari dua cara berikut ini:
Menggunakan opsi yang disediakan oleh pustaka instrumentasi.
Tambahkan prosesor rentang kustom.
Tip
Keuntungan menggunakan opsi yang disediakan oleh pustaka instrumentasi, ketika opsi tersebut ada, yaitu tersedianya seluruh konteks. Sebagai hasilnya, pengguna dapat memilih untuk menambahkan atau memfilter lebih banyak atribut. Sebagai contoh, opsi memperkaya di pustaka instrumentasi HttpClient memberikan pengguna akses ke httpRequestMessage itu sendiri. Mereka dapat memilih apa pun darinya dan menyimpannya sebagai atribut.
Banyak perpustakaan instrumentasi memberikan opsi yang dapat memperkaya. Sebagai panduan, lihat file readme dari pustaka instrumentasi individual:
Tambahkan prosesor yang ditampilkan di sini sebelum Pengekspor 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();
Tambahkan ActivityEnrichingProcessor.cs kode berikut ke proyek Anda:
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");
}
}
Anda dapat menggunakan opentelemetry-api untuk menambahkan atribut ke rentang.
Menambahkan satu atau beberapa atribut rentang mengisi bidang di requeststabel , , dependenciestraces, atau exceptions .customDimensions
Tambahkan opentelemetry-api-1.0.0.jar (atau yang lebih baru) ke aplikasi Anda:
...
# 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],
)
...
Tambahkan SpanEnrichingProcessor kode berikut ke proyek Anda:
# 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"
Mengatur IP pengguna
Anda dapat mengisi bidang client_IP untuk permintaan dengan mengatur atribut pada rentang. Application Insights menggunakan alamat IP untuk menghasilkan atribut lokasi pengguna dan kemudian membuangnya secara default.
Gunakan contoh properti kustom, tetapi ganti baris kode berikut di 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>");
Gunakan contoh properti kustom, tetapi ganti baris kode berikut di 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>");
Java secara otomatis mengisi bidang ini.
Bidang ini diisi secara otomatis.
Gunakan contoh properti kustom, tetapi ganti baris kode berikut:
...
// 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>";
}
}
Gunakan contoh properti kustom, tetapi ganti baris kode berikut di SpanEnrichingProcessor.py:
# Set the `http.client_ip` attribute of the span to the specified IP address.
span._attributes["http.client_ip"] = "<IP Address>"
Mengatur ID pengguna atau ID pengguna terautentikasi
Anda dapat mengisi bidang user_Id atau user_AuthenticatedId untuk permintaan dengan menggunakan panduan berikut. ID pengguna adalah pengidentifikasi pengguna anonim. ID Pengguna Terautentikasi adalah pengidentifikasi pengguna yang diketahui.
Penting
Lihat undang-undang privasi yang berlaku sebelum Anda menetapkan ID Pengguna Terautentikasi.
Gunakan contoh properti kustom, tetapi ganti baris kode berikut:
...
// 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>";
}
}
Gunakan contoh properti kustom, tetapi ganti baris kode berikut:
# Set the `enduser.id` attribute of the span to the specified user ID.
span._attributes["enduser.id"] = "<User ID>"
Pustaka pengelogan Python disusun otomatis. Anda dapat melampirkan dimensi kustom ke log Anda dengan meneruskan kamus ke extra argumen log Anda:
...
# Create a warning log message with the properties "key1" and "value1".
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
Filter telemetri
Anda dapat menggunakan cara-cara berikut untuk menyaring telemetri sebelum meninggalkan aplikasi Anda.
Tambahkan prosesor yang ditampilkan di sini sebelum menambahkan Azure Monitor.
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry tracer provider to add a new processor named ActivityFilteringProcessor.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddProcessor(new ActivityFilteringProcessor()));
// Configure the OpenTelemetry tracer provider to add a new source named "ActivitySourceName".
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddSource("ActivitySourceName"));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core application.
var app = builder.Build();
// Start the ASP.NET Core application.
app.Run();
Tambahkan ActivityFilteringProcessor.cs kode berikut ke proyek Anda:
public class ActivityFilteringProcessor : BaseProcessor<Activity>
{
// The OnStart method is called when an activity is started. This is the ideal place to filter activities.
public override void OnStart(Activity activity)
{
// prevents all exporters from exporting internal activities
if (activity.Kind == ActivityKind.Internal)
{
activity.IsAllDataRequested = false;
}
}
}
Jika sumber tertentu tidak ditambahkan secara eksplisit dengan menggunakan AddSource("ActivitySourceName"), maka tidak ada aktivitas yang dibuat dengan menggunakan sumber tersebut yang diekspor.
Banyak pustaka instrumentasi menyediakan opsi filter. Sebagai panduan, lihat file readme dari pustaka instrumentasi individual:
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("OTel.AzureMonitor.Demo") // Add a source named "OTel.AzureMonitor.Demo".
.AddProcessor(new ActivityFilteringProcessor()) // Add a new processor named ActivityFilteringProcessor.
.AddAzureMonitorTraceExporter() // Add the Azure Monitor trace exporter.
.Build();
Tambahkan ActivityFilteringProcessor.cs kode berikut ke proyek Anda:
public class ActivityFilteringProcessor : BaseProcessor<Activity>
{
// The OnStart method is called when an activity is started. This is the ideal place to filter activities.
public override void OnStart(Activity activity)
{
// prevents all exporters from exporting internal activities
if (activity.Kind == ActivityKind.Internal)
{
activity.IsAllDataRequested = false;
}
}
}
Jika sumber tertentu tidak ditambahkan secara eksplisit dengan menggunakan AddSource("ActivitySourceName"), maka tidak ada aktivitas yang dibuat dengan menggunakan sumber tersebut yang diekspor.
// Import the useAzureMonitor function and the ApplicationInsightsOptions class from the @azure/monitor-opentelemetry package.
const { useAzureMonitor, ApplicationInsightsOptions } = require("@azure/monitor-opentelemetry");
// Import the HttpInstrumentationConfig class from the @opentelemetry/instrumentation-http package.
const { HttpInstrumentationConfig }= require("@opentelemetry/instrumentation-http");
// Import the IncomingMessage and RequestOptions classes from the http and https packages, respectively.
const { IncomingMessage } = require("http");
const { RequestOptions } = require("https");
// Create a new HttpInstrumentationConfig object.
const httpInstrumentationConfig: HttpInstrumentationConfig = {
enabled: true,
ignoreIncomingRequestHook: (request: IncomingMessage) => {
// Ignore OPTIONS incoming requests.
if (request.method === 'OPTIONS') {
return true;
}
return false;
},
ignoreOutgoingRequestHook: (options: RequestOptions) => {
// Ignore outgoing requests with the /test path.
if (options.path === '/test') {
return true;
}
return false;
}
};
// Create a new ApplicationInsightsOptions object.
const config: ApplicationInsightsOptions = {
instrumentationOptions: {
http: {
httpInstrumentationConfig
}
}
};
// Enable Azure Monitor integration using the useAzureMonitor function and the ApplicationInsightsOptions object.
useAzureMonitor(config);
Gunakan prosesor kustom. Anda dapat menggunakan prosesor rentang kustom untuk mengecualikan rentang tertentu agar tidak diekspor. Untuk menandai rentang agar tidak diekspor, atur TraceFlag ke DEFAULT.
Gunakan contoh properti kustom, tetapi ganti baris kode berikut:
// Import the necessary packages.
const { SpanKind, TraceFlags } = require("@opentelemetry/api");
const { ReadableSpan, Span, SpanProcessor } = require("@opentelemetry/sdk-trace-base");
// Create a new SpanEnrichingProcessor class.
class SpanEnrichingProcessor implements SpanProcessor {
forceFlush(): Promise<void> {
return Promise.resolve();
}
shutdown(): Promise<void> {
return Promise.resolve();
}
onStart(_span: Span): void {}
onEnd(span) {
// If the span is an internal span, set the trace flags to NONE.
if(span.kind == SpanKind.INTERNAL){
span.spanContext().traceFlags = TraceFlags.NONE;
}
}
}
Kecualikan URL dengan OTEL_PYTHON_EXCLUDED_URLS variabel lingkungan:
Melakukannya mengecualikan titik akhir yang diperlihatkan dalam contoh Flask berikut:
...
# Import the Flask and Azure Monitor OpenTelemetry SDK libraries.
import flask
from azure.monitor.opentelemetry import configure_azure_monitor
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Create a Flask application.
app = flask.Flask(__name__)
# Define a route. Requests sent to this endpoint will not be tracked due to
# flask_config configuration.
@app.route("/ignore")
def ignore():
return "Request received but not tracked."
...
Gunakan prosesor kustom. Anda dapat menggunakan prosesor rentang kustom untuk mengecualikan rentang tertentu agar tidak diekspor. Untuk menandai rentang agar tidak diekspor, atur TraceFlag ke DEFAULT:
...
# Import the necessary libraries.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
# Configure the custom span processors to include span filter processor.
span_processors=[span_filter_processor],
)
...
Tambahkan SpanFilteringProcessor kode berikut ke proyek Anda:
# Import the necessary libraries.
from opentelemetry.trace import SpanContext, SpanKind, TraceFlags
from opentelemetry.sdk.trace import SpanProcessor
# Define a custom span processor called `SpanFilteringProcessor`.
class SpanFilteringProcessor(SpanProcessor):
# Prevents exporting spans from internal activities.
def on_start(self, span, parent_context):
# Check if the span is an internal activity.
if span._kind is SpanKind.INTERNAL:
# Create a new span context with the following properties:
# * The trace ID is the same as the trace ID of the original span.
# * The span ID is the same as the span ID of the original span.
# * The is_remote property is set to `False`.
# * The trace flags are set to `DEFAULT`.
# * The trace state is the same as the trace state of the original span.
span._context = SpanContext(
span.context.trace_id,
span.context.span_id,
span.context.is_remote,
TraceFlags(TraceFlags.DEFAULT),
span.context.trace_state,
)
Dapatkan ID jejak atau ID rentang
Anda bisa mendapatkan Trace ID dan Span ID rentang yang saat ini aktif menggunakan langkah-langkah berikut.
Kelas Activity dan ActivitySource dari namespace layanan System.Diagnostics, masing-masing mewakili konsep OpenTelemetry dari Span dan Tracer. Hal itu karena bagian dari OpenTelemetry yang melacak API dimasukkan secara langsung ke dalam runtime bahasa umum .NET. Untuk mempelajari selengkapnya, lihat Pengenalan API Pelacakan OpenTelemetry .NET.
// 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();
Catatan
Kelas Activity dan ActivitySource dari namespace layanan System.Diagnostics, masing-masing mewakili konsep OpenTelemetry dari Span dan Tracer. Hal itu karena bagian dari OpenTelemetry yang melacak API dimasukkan secara langsung ke dalam runtime bahasa umum .NET. Untuk mempelajari selengkapnya, lihat Pengenalan API Pelacakan OpenTelemetry .NET.
// 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();
Anda dapat menggunakan opentelemetry-api untuk mendapatkan ID jejak atau ID rentang.
Tambahkan opentelemetry-api-1.0.0.jar (atau yang lebih baru) ke aplikasi Anda:
Dapatkan ID pelacakan permintaan dan ID rentang dalam kode Anda:
// 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;
Dapatkan ID pelacakan permintaan dan ID rentang dalam kode Anda:
# 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