تعتبر حاليا جميع مقاييس OpenTelemetry سواء تم جمعها تلقائيا من مكتبات الأجهزة أو التي تم جمعها يدويا من الترميز المخصص "مقاييس مخصصة" ل Application Insights لأغراض الفوترة. اعرف المزيد.
إضافة مكتبة أجهزة المجتمع
يمكنك جمع المزيد من البيانات تلقائيا عند تضمين مكتبات الأجهزة من مجتمع OpenTelemetry.
تنبيه
نحن لا ندعم أو نضمن جودة مكتبات الأجهزة المجتمعية. اقتراح واحد لنشرنا أو نشره أو التصويت عليه في مجتمع الملاحظات لدينا. كن على علم، يعتمد بعضها على مواصفات OpenTelemetry التجريبية وقد يقدم تغييرات كسرية مستقبلية.
// 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();
لا يمكنك توسيع Java Distro مع مكتبات الأجهزة المجتمعية. لطلب تضمين مكتبة أدوات أخرى، افتح مشكلة على صفحة GitHub الخاصة بنا. يمكنك العثور على ارتباط إلى صفحة GitHub في الخطوات التالية.
// 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
});
لإضافة مكتبة أجهزة المجتمع (غير مدعومة/مضمنة رسميا في توزيعة Azure Monitor)، يمكنك استخدام الأجهزة مباشرة. يمكن العثور على قائمة مكتبات الأجهزة المجتمعية هنا.
إشعار
لا يوصى باستخدام مكتبة أدوات مدعومة يدويا بالتزامن مع instrument() توزيعة configure_azure_monitor() الأجهزة. هذا ليس سيناريو مدعوما وقد تحصل على سلوك غير مطلوب لبيانات تتبع الاستخدام الخاصة بك.
# 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())
جمع بيانات تتبع الاستخدام المخصصة
يشرح هذا القسم كيفية جمع بيانات تتبع الاستخدام المخصصة من التطبيق الخاص بك.
اعتمادا على اللغة ونوع الإشارة، هناك طرق مختلفة لجمع بيانات تتبع الاستخدام المخصصة، بما في ذلك:
يمثل الجدول التالي أنواع بيانات تتبع الاستخدام المخصصة المدعومة حاليا:
اللغة
أحداث مخصصة
مقاييس مخصصة
التبعيات
استثناءات
طرق عرض الصفحة
الطلبات
Traces
ASP.NET Core
OpenTelemetry API
نعم
نعم
نعم
نعم
ILogger API
نعم
واجهة برمجة تطبيقات الذكاء الاصطناعي الكلاسيكية
Java
OpenTelemetry API
نعم
نعم
نعم
نعم
Logback, , Log4jJUL
نعم
نعم
قياسات ميكرومتر
نعم
واجهة برمجة تطبيقات الذكاء الاصطناعي الكلاسيكية
نعم
نعم
نعم
نعم
نعم
نعم
نعم
Node.js
OpenTelemetry API
نعم
نعم
نعم
نعم
Python
OpenTelemetry API
نعم
نعم
نعم
نعم
وحدة تسجيل Python
نعم
ملحق الأحداث
نعم
نعم
إشعار
يستمع Application Insights Java 3.x إلى بيانات تتبع الاستخدام التي يتم إرسالها إلى واجهة برمجة تطبيقات Application Insights الكلاسيكية. وبالمثل، يجمع Application Insights Node.js 3.x الأحداث التي تم إنشاؤها باستخدام واجهة برمجة تطبيقات Application Insights الكلاسيكية. وهذا يجعل الترقية أسهل ويملأ فجوة في دعم بيانات تتبع الاستخدام المخصص لدينا حتى يتم دعم جميع أنواع بيانات تتبع الاستخدام المخصصة عبر واجهة برمجة تطبيقات القياس عن بعد المفتوح.
إضافة القياسات المخصصة
في هذا السياق، تشير المقاييس المخصصة إلى أدوات التعليمات البرمجية يدويا لجمع مقاييس إضافية تتجاوز ما تجمعه مكتبات أدوات القياس المفتوح تلقائيا.
تقدم OpenTelemetry API ست "أدوات" قياسية لتغطية سيناريوهات القياس المختلفة وتحتاج إلى اختيار "نوع التجميع" الصحيح عند تصور المقاييس في Metrics Explorer. هذا المطلب صحيح عند استخدام OpenTelemetry Metric API لإرسال المقاييس وعند استخدام مكتبة الأجهزة.
عادة ما تكون أنواع التجميع التي تتجاوز ما يظهر في الجدول غير ذات معنى.
تصف مواصفات OpenTelemetry الأدوات وتوفر أمثلة على الوقت الذي قد تستخدم فيه كل منها.
تلميح
المدرج التكراري هو الأكثر تنوعا وأكثر مكافئا لواجهة برمجة تطبيقات Application Insights GetMetric Classic. يقوم Azure Monitor حاليا بتسطيح أداة المدرج التكراري في أنواع التجميع الخمسة المدعومة لدينا، كما أن دعم النسب المئوية قيد التنفيذ. على الرغم من أنها أقل تنوعا، فإن أدوات القياس المفتوح الأخرى لها تأثير أقل على أداء التطبيق الخاص بك.
// 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 يجب تهيئة باستخدام نفس الاسم.
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new histogram metric named "FruitSalePrice".
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");
// Create a new Random object.
var rand = new Random();
// Record a few random sale prices for apples and lemons, with different colors.
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "green"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Create a new Histogram metric named "FruitSalePrice".
// This metric will track the distribution of fruit sale prices.
Histogram<long> myFruitSalePrice = meter.CreateHistogram<long>("FruitSalePrice");
// Create a new Random object. This object will be used to generate random sale prices.
var rand = new Random();
// Record a few random sale prices for apples and lemons, with different colors.
// Each record includes a timestamp, a value, and a set of attributes.
// The attributes can be used to filter and analyze the metric data.
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "green"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "apple"), new("color", "red"));
myFruitSalePrice.Record(rand.Next(1, 1000), new("name", "lemon"), new("color", "yellow"));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
histogram.record(1.0);
histogram.record(100.0);
histogram.record(30.0);
}
}
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the meter for the "testMeter" namespace
const meter = metrics.getMeter("testMeter");
// Create a histogram metric
let histogram = meter.createHistogram("histogram");
// Record values to the histogram metric with different tags
histogram.record(1, { "testKey": "testValue" });
histogram.record(30, { "testKey": "testValue2" });
histogram.record(100, { "testKey2": "testValue" });
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Get a meter provider and a meter with the name "otel_azure_monitor_histogram_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_histogram_demo")
# Record three values to the histogram.
histogram = meter.create_histogram("histogram")
histogram.record(1.0, {"test_key": "test_value"})
histogram.record(100.0, {"test_key2": "test_value"})
histogram.record(30.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
// 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 يجب تهيئة باستخدام نفس الاسم.
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new counter metric named "MyFruitCounter".
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
// Record the number of fruits sold, grouped by name and color.
myFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(1, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(2, new("name", "apple"), new("color", "green"));
myFruitCounter.Add(5, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(4, new("name", "lemon"), new("color", "yellow"));
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Create a new counter metric named "MyFruitCounter".
// This metric will track the number of fruits sold.
Counter<long> myFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
// Record the number of fruits sold, grouped by name and color.
myFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(1, new("name", "lemon"), new("color", "yellow"));
myFruitCounter.Add(2, new("name", "apple"), new("color", "green"));
myFruitCounter.Add(5, new("name", "apple"), new("color", "red"));
myFruitCounter.Add(4, new("name", "lemon"), new("color", "yellow"));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
LongCounter myFruitCounter = meter
.counterBuilder("MyFruitCounter")
.build();
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "green"));
myFruitCounter.add(5, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(4, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
}
}
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the meter for the "testMeter" namespace
const meter = metrics.getMeter("testMeter");
// Create a counter metric
let counter = meter.createCounter("counter");
// Add values to the counter metric with different tags
counter.add(1, { "testKey": "testValue" });
counter.add(5, { "testKey2": "testValue" });
counter.add(3, { "testKey": "testValue2" });
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Get a meter provider and a meter with the name "otel_azure_monitor_counter_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_counter_demo")
# Create a counter metric with the name "counter".
counter = meter.create_counter("counter")
# Add three values to the counter.
# The first argument to the `add()` method is the value to add.
# The second argument is a dictionary of dimensions.
# Dimensions are used to group related metrics together.
counter.add(1.0, {"test_key": "test_value"})
counter.add(5.0, {"test_key2": "test_value"})
counter.add(3.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
// 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 يجب تهيئة باستخدام نفس الاسم.
// Get the current process.
var process = Process.GetCurrentProcess();
// Create a new meter named "OTel.AzureMonitor.Demo".
var meter = new Meter("OTel.AzureMonitor.Demo");
// Create a new observable gauge metric named "Thread.State".
// This metric will track the state of each thread in the current process.
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));
private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
// Iterate over all threads in the current process.
foreach (ProcessThread thread in process.Threads)
{
// Create a measurement for each thread, including the thread state, process ID, and thread ID.
yield return new((int)thread.ThreadState, new("ProcessId", process.Id), new("ThreadId", thread.Id));
}
}
public class Program
{
// Create a static readonly Meter object named "OTel.AzureMonitor.Demo".
// This meter will be used to track metrics about the application.
private static readonly Meter meter = new("OTel.AzureMonitor.Demo");
public static void Main()
{
// Create a new MeterProvider object using the OpenTelemetry SDK.
// The MeterProvider object is responsible for managing meters and sending
// metric data to exporters.
// It is important to keep the MetricsProvider instance active
// throughout the process lifetime.
//
// The MeterProviderBuilder is configured to add a meter named
// "OTel.AzureMonitor.Demo" and an Azure Monitor metric exporter.
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("OTel.AzureMonitor.Demo")
.AddAzureMonitorMetricExporter()
.Build();
// Get the current process.
var process = Process.GetCurrentProcess();
// Create a new observable gauge metric named "Thread.State".
// This metric will track the state of each thread in the current process.
ObservableGauge<int> myObservableGauge = meter.CreateObservableGauge("Thread.State", () => GetThreadState(process));
// Display a message to the user and wait for them to press Enter.
// This allows the user to see the message and the console before the
// application exits.
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
private static IEnumerable<Measurement<int>> GetThreadState(Process process)
{
// Iterate over all threads in the current process.
foreach (ProcessThread thread in process.Threads)
{
// Create a measurement for each thread, including the thread state, process ID, and thread ID.
yield return new((int)thread.ThreadState, new("ProcessId", process.Id), new("ThreadId", thread.Id));
}
}
}
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;
public class Program {
public static void main(String[] args) {
Meter meter = GlobalOpenTelemetry.getMeter("OTEL.AzureMonitor.Demo");
meter.gaugeBuilder("gauge")
.buildWithCallback(
observableMeasurement -> {
double randomNumber = Math.floor(Math.random() * 100);
observableMeasurement.record(randomNumber, Attributes.of(AttributeKey.stringKey("testKey"), "testValue"));
});
}
}
// Import the useAzureMonitor function and the metrics module from the @azure/monitor-opentelemetry and @opentelemetry/api packages, respectively.
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration.
useAzureMonitor();
// Get the meter for the "testMeter" meter name.
const meter = metrics.getMeter("testMeter");
// Create an observable gauge metric with the name "gauge".
let gauge = meter.createObservableGauge("gauge");
// Add a callback to the gauge metric. The callback will be invoked periodically to generate a new value for the gauge metric.
gauge.addCallback((observableResult: ObservableResult) => {
// Generate a random number between 0 and 99.
let randomNumber = Math.floor(Math.random() * 100);
// Set the value of the gauge metric to the random number.
observableResult.observe(randomNumber, {"testKey": "testValue"});
});
# Import the necessary packages.
from typing import Iterable
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
from opentelemetry.metrics import CallbackOptions, Observation
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Get a meter provider and a meter with the name "otel_azure_monitor_gauge_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_gauge_demo")
# Define two observable gauge generators.
# The first generator yields a single observation with the value 9.
# The second generator yields a sequence of 10 observations with the value 9 and a different dimension value for each observation.
def observable_gauge_generator(options: CallbackOptions) -> Iterable[Observation]:
yield Observation(9, {"test_key": "test_value"})
def observable_gauge_sequence(options: CallbackOptions) -> Iterable[Observation]:
observations = []
for i in range(10):
observations.append(
Observation(9, {"test_key": i})
)
return observations
# Create two observable gauges using the defined generators.
gauge = meter.create_observable_gauge("gauge", [observable_gauge_generator])
gauge2 = meter.create_observable_gauge("gauge2", [observable_gauge_sequence])
# Wait for background execution.
input()
إضافة استثناءات مخصصة
حدد مكتبات الأجهزة التي تقوم تلقائيا بالإبلاغ عن الاستثناءات إلى Application Insights.
ومع ذلك، قد تحتاج إلى الإبلاغ يدويا عن استثناءات تتجاوز ما تبلغ به مكتبات الأجهزة.
على سبيل المثال، لا يتم الإبلاغ عادة عن الاستثناءات التي تم التقاطها بواسطة التعليمات البرمجية الخاصة بك. قد ترغب في الإبلاغ عنها لجذب الانتباه في التجارب ذات الصلة بما في ذلك قسم الفشل وطرق عرض المعاملات الشاملة.
// 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);
}
}
لتسجيل استثناء باستخدام 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" });
}
لتسجيل استثناء باستخدام نشاط:
// 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);
}
}
لتسجيل استثناء باستخدام 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" });
}
يمكنك استخدام opentelemetry-api لتحديث حالة استثناءات نطاق أو سجل.
إضافة opentelemetry-api-1.0.0.jar (أو أحدث) إلى التطبيق الخاص بك:
// 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);
}
يتم تنفيذ OpenTelemetry Python SDK بطريقة يتم من خلالها التقاط الاستثناءات التي يتم طرحها وتسجيلها تلقائيا. راجع نموذج التعليمات البرمجية التالي للحصول على مثال لهذا السلوك.
# 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")
إذا كنت ترغب في تسجيل الاستثناءات يدويا، يمكنك تعطيل هذا الخيار داخل مدير السياق واستخدامه record_exception() مباشرة كما هو موضح في المثال التالي:
...
# 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)
...
إضافة امتدادات مخصصة
قد تحتاج إلى إضافة نطاق مخصص في سيناريوهين. أولا، عندما يكون هناك طلب تبعية لم يتم جمعه بالفعل بواسطة مكتبة الأجهزة. ثانيا، عندما ترغب في نمذجة عملية تطبيق كامتداد في طريقة عرض المعاملة من طرف إلى طرف.
Activityتمثل ActivitySource الفئات و من System.Diagnostics مساحة الاسم مفاهيم القياس المفتوح Span و Tracer على التوالي. يمكنك إنشاء ActivitySource مباشرة باستخدام الدالة الإنشائية الخاصة به بدلًا من استخدام TracerProvider. يجب أن تكون كل فئة ActivitySource متصلة بشكل صريح بـTracerProvider باستخدام AddSource(). وذلك لأن أجزاء من واجهة برمجة تطبيقات تتبع OpenTelemetry يتم دمجها مباشرة في وقت التشغيل .NET. لمعرفة المزيد، راجع مقدمة إلى OpenTelemetry .NET Tracing API.
// 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افتراضيات إلى ActivityKind.Internal، ولكن يمكنك توفير أي .ActivityKindActivityKind.Client، ActivityKind.Producerويتم تعيين و ActivityKind.Internal إلى Application Insights dependencies.
ActivityKind.Server ويتم تعيينها ActivityKind.Consumer إلى Application Insights requests.
إشعار
Activityتمثل ActivitySource الفئات و من System.Diagnostics مساحة الاسم مفاهيم القياس المفتوح Span و Tracer على التوالي. يمكنك إنشاء ActivitySource مباشرة باستخدام الدالة الإنشائية الخاصة به بدلًا من استخدام TracerProvider. يجب أن تكون كل فئة ActivitySource متصلة بشكل صريح بـTracerProvider باستخدام AddSource(). وذلك لأن أجزاء من واجهة برمجة تطبيقات تتبع OpenTelemetry يتم دمجها مباشرة في وقت التشغيل .NET. لمعرفة المزيد، راجع مقدمة إلى OpenTelemetry .NET Tracing API.
// 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افتراضيات إلى ActivityKind.Internal، ولكن يمكنك توفير أي .ActivityKindActivityKind.Client، ActivityKind.Producerويتم تعيين و ActivityKind.Internal إلى Application Insights dependencies.
ActivityKind.Server ويتم تعيينها ActivityKind.Consumer إلى Application Insights requests.
استخدام التعليق التوضيحي OpenTelemetry
أبسط طريقة لإضافة الامتدادات الخاصة بك هي باستخدام التعليق التوضيحي ل @WithSpan OpenTelemetry.
تملأ المسافات requests و dependenciesالجداول في Application Insights.
إضافة opentelemetry-instrumentation-annotations-1.32.0.jar (أو أحدث) إلى التطبيق الخاص بك:
بشكل افتراضي، ينتهي النطاق في dependencies الجدول بنوع InProcالتبعية .
بالنسبة للأساليب التي تمثل مهمة خلفية لم يتم التقاطها بواسطة البنية التلقائية، نوصي بتطبيق السمة kind = SpanKind.SERVER على @WithSpan التعليق التوضيحي للتأكد من ظهورها في جدول Application Insights requests .
استخدام OpenTelemetry API
إذا لم يفي التعليق التوضيحي السابق ل OpenTelemetry @WithSpan باحتياجاتك، يمكنك إضافة الامتدادات باستخدام واجهة برمجة تطبيقات OpenTelemetry.
إضافة opentelemetry-api-1.0.0.jar (أو أحدث) إلى التطبيق الخاص بك:
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = GlobalOpenTelemetry.getTracer("com.example");
أنشئ امتدادا، واجعله محدثا، ثم أنهه:
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();
يمكن استخدام OpenTelemetry API لإضافة النطاقات الخاصة بك، والتي تظهر في requests الجداول و dependencies في Application Insights.
يوضح مثال التعليمات البرمجية tracer.start_as_current_span() كيفية استخدام الأسلوب للبدء، وجعل النطاق الحالي، وإنهاء النطاق ضمن سياقه.
...
# 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)
...
بشكل افتراضي، يكون النطاق في dependencies الجدول بنوع تبعية من InProc.
إذا كان الأسلوب الخاص بك يمثل مهمة خلفية لم يتم التقاطها بالفعل بواسطة البنية التلقائية، نوصي بتعيين السمة kind = SpanKind.SERVER للتأكد من ظهورها في جدول 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.
...
إرسال بيانات تتبع الاستخدام المخصصة باستخدام واجهة برمجة تطبيقات Application Insights الكلاسيكية
نوصي باستخدام واجهات برمجة التطبيقات OpenTelemetry كلما أمكن ذلك، ولكن قد تكون هناك بعض السيناريوهات عندما تضطر إلى استخدام واجهة برمجة تطبيقات Application Insights الكلاسيكية.
إذا كنت ترغب في إضافة أحداث مخصصة أو الوصول إلى واجهة برمجة تطبيقات Application Insights، فاستبدل الحزمة @azure/monitor-opentelemetry بحزمة applicationinsightsالإصدار 3 Beta. يوفر نفس الأساليب والواجهات، وتنطبق جميع نماذج التعليمات البرمجية على @azure/monitor-opentelemetry حزمة الإصدار 3 Beta.
// Import the TelemetryClient class from the Application Insights SDK for JavaScript.
const { TelemetryClient } = require("applicationinsights");
// Create a new TelemetryClient instance.
const telemetryClient = new TelemetryClient();
ثم استخدم TelemetryClient لإرسال بيانات تتبع الاستخدام المخصصة:
حدث
// Create an event telemetry object.
let eventTelemetry = {
name: "testEvent"
};
// Send the event telemetry object to Azure Monitor Application Insights.
telemetryClient.trackEvent(eventTelemetry);
السجلات
// Create a trace telemetry object.
let traceTelemetry = {
message: "testMessage",
severity: "Information"
};
// Send the trace telemetry object to Azure Monitor Application Insights.
telemetryClient.trackTrace(traceTelemetry);
استثناءات
// 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);
}
على عكس اللغات الأخرى، لا تحتوي Python على Application Insights SDK. يمكنك تلبية جميع احتياجات المراقبة الخاصة بك باستخدام Azure Monitor OpenTelemetry Distro، باستثناء إرسال customEvents. حتى تستقر واجهة برمجة تطبيقات أحداث القياس المفتوح، استخدم ملحق أحداث Azure Monitor مع Azure Monitor OpenTelemetry Distro لإرسالها customEvents إلى Application Insights.
track_event استخدم واجهة برمجة التطبيقات المقدمة في الملحق لإرسال أحداث مخصصة.
...
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()
...
تعديل القياس عن بُعد
يشرح هذا القسم كيفية تعديل بيانات تتبع الاستخدام.
إضافة سمات النطاق
يمكن أن تتضمن هذه السمات إضافة خاصية مخصص إلى قياسك عن بُعد. يمكنك أيضًا استخدام سمات لتعيين الحقول الاختيارية في مخطط Application Insights، مثل IP العميل.
إضافة خاصية مخصصة إلى Span
يتم تصدير أي سمات تضيفها إلى الامتدادات كخصائص مخصصة. يقومون بتعبئة حقل customDimensions في جدول الطلبات أو التبعيات أو التتبعات أو الاستثناءات.
تتمثل ميزة استخدام الخيارات التي توفرها مكتبات الأجهزة، عندما تكون متاحة، في أن السياق بأكمله متاح. ونتيجة لذلك، يمكن للمستخدمين تحديد لإضافة المزيد من السمات أو تصفيتها. على سبيل المثال، يتيح خيار الإثراء في مكتبة الأجهزة HttpClient للمستخدمين الوصول إلى HttpRequestMessage وHttpResponseMessage نفسه. يمكنهم تحديد أي شيء منه وتخزينه كسمة.
توفر العديد من مكتبات الأجهزة خيارا تثري. للحصول على إرشادات، راجع ملفات readme لمكتبات الأجهزة الفردية:
// 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();
أضف ActivityEnrichingProcessor.cs إلى مشروعك باستخدام التعليمات البرمجية التالية:
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");
}
}
لإضافة سمات النطاق، استخدم أي من الطريقتين التاليتين:
استخدم الخيارات المتوفرة من قبل مكتبات الأجهزة.
إضافة معالج نطاق مخصص.
تلميح
تتمثل ميزة استخدام الخيارات التي توفرها مكتبات الأجهزة، عندما تكون متاحة، في أن السياق بأكمله متاح. ونتيجة لذلك، يمكن للمستخدمين تحديد لإضافة المزيد من السمات أو تصفيتها. على سبيل المثال، خيار الإثراء في مكتبة تقرير حالة النظام HttpClient، يمنح المستخدمين الوصول إلى httpRequestMessage نفسها. يمكنهم تحديد أي شيء منه وتخزينه كسمة.
توفر العديد من مكتبات الأجهزة خيارا تثري. للحصول على إرشادات، راجع ملفات readme لمكتبات الأجهزة الفردية:
// 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();
أضف ActivityEnrichingProcessor.cs إلى مشروعك باستخدام التعليمات البرمجية التالية:
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");
}
}
يمكنك استخدام opentelemetry-api لإضافة سمات إلى النطاقات.
تؤدي إضافة سمة امتداد واحدة أو أكثر إلى customDimensions تعبئة الحقل في requestsالجدول أو dependenciestracesأو أو .exceptions
إضافة opentelemetry-api-1.0.0.jar (أو أحدث) إلى التطبيق الخاص بك:
...
# 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],
)
...
أضف SpanEnrichingProcessor إلى مشروعك باستخدام التعليمات البرمجية التالية:
# 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"
تعيين IP المستخدم
يمكنك ملء حقل client_IP للطلبات عن طريق تعيين سمة على النطاق. يستخدم التطبيق Insights عنوان IP لإنشاء سمات موقع المستخدم ثم يتجاهله بشكل افتراضي.
استخدم مثال إضافة خاصية مخصصة، إلا تبديل التعليمات البرمجية التالية في 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>");
استخدم مثال إضافة خاصية مخصصة، إلا تبديل التعليمات البرمجية التالية في ActivityEnrichingProcessor.cs:
// Add the client IP address to the activity as a tag.
// only applicable in case of activity.Kind == Server
activity.SetTag("http.client_ip", "<IP Address>");
...
// 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>";
}
}
استخدم مثال إضافة خاصية مخصصة، إلا تبديل التعليمات البرمجية التالية في SpanEnrichingProcessor.py:
# Set the `http.client_ip` attribute of the span to the specified IP address.
span._attributes["http.client_ip"] = "<IP Address>"
تعيين معرف المستخدم أو معرف المستخدم المصادق عليه
يمكنك ملء حقل user_Id أو user_AuthenticatedId للطلبات باستخدام الإرشادات التالية. معرف المستخدم هو معرف مستخدم مجهول. معرف المستخدم المصادق عليه هو معرف مستخدم معروف.
هام
راجع قوانين الخصوصية المعمول بها قبل تعيين معرف المستخدم المصادق عليه.
...
// 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>";
}
}
مكتبة تسجيل Python مفسرة تلقائيا. يمكنك إرفاق أبعاد مخصصة بسجلاتك عن طريق تمرير قاموس إلى وسيطة extra سجلاتك.
...
# Create a warning log message with the properties "key1" and "value1".
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
تصفية التتبع
يمكنك استخدام الطرق التالية لتصفية القياس عن بعد قبل مغادرة التطبيق الخاص بك.
// 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();
أضف ActivityFilteringProcessor.cs إلى مشروعك باستخدام التعليمات البرمجية التالية:
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;
}
}
}
إذا لم تتم إضافة مصدر معين بشكل صريح باستخدام AddSource("ActivitySourceName")، فلن يتم تصدير أي من الأنشطة التي تم إنشاؤها باستخدام هذا المصدر.
توفر العديد من مكتبات الأجهزة خيارا تثري. للحصول على إرشادات، راجع ملفات readme لمكتبات الأجهزة الفردية:
// 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();
أضف ActivityFilteringProcessor.cs إلى مشروعك باستخدام التعليمات البرمجية التالية:
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;
}
}
}
إذا لم تتم إضافة مصدر معين بشكل صريح باستخدام AddSource("ActivitySourceName")، فلن يتم تصدير أي من الأنشطة التي تم إنشاؤها باستخدام هذا المصدر.
// 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);
استخدم معالجًا مخصصًا. يمكنك استخدام معالج نطاق مخصص لاستبعاد امتدادات معينة من تصديرها. لوضع علامة على النطاقات التي لا يتم تصديرها، قم بتعيينها TraceFlag إلى DEFAULT.
استخدم مثال إضافة خاصية مخصصة، إلا تبديل التعليمات البرمجية التالية:
// 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;
}
}
}
استبعاد عنوان URL مع OTEL_PYTHON_EXCLUDED_URLS متغير البيئة:
يؤدي القيام بذلك إلى استبعاد نقطة النهاية الموضحة في مثال Flask التالي:
...
# Import the Flask and Azure Monitor OpenTelemetry SDK libraries.
import flask
from azure.monitor.opentelemetry import configure_azure_monitor
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Create a Flask application.
app = flask.Flask(__name__)
# Define a route. Requests sent to this endpoint will not be tracked due to
# flask_config configuration.
@app.route("/ignore")
def ignore():
return "Request received but not tracked."
...
استخدم معالجًا مخصصًا. يمكنك استخدام معالج نطاق مخصص لاستبعاد امتدادات معينة من تصديرها. لوضع علامة على النطاقات التي لا يتم تصديرها، قم بتعيينها TraceFlag إلى 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],
)
...
أضف SpanFilteringProcessor إلى مشروعك باستخدام التعليمات البرمجية التالية:
# 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,
)
الحصول على معرف التتبع أو معرف النطاق
قد تحتاج إلى الحصول على معرف التتبع أو معرف النطاق. إذا كانت لديك سجلات تم إرسالها إلى وجهة أخرى غير Application Insights، ففكر في إضافة معرف التتبع أو معرف النطاق. يؤدي القيام بذلك إلى تمكين ارتباط أفضل عند تصحيح الأخطاء وتشخيص المشكلات.
Activityتمثل ActivitySource الفئات و من System.Diagnostics مساحة الاسم مفاهيم القياس المفتوح Span و Tracer على التوالي. وذلك لأن أجزاء من واجهة برمجة تطبيقات تتبع OpenTelemetry يتم دمجها مباشرة في وقت التشغيل .NET. لمعرفة المزيد، راجع مقدمة إلى OpenTelemetry .NET Tracing API.
// 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();
إشعار
Activityتمثل ActivitySource الفئات و من System.Diagnostics مساحة الاسم مفاهيم القياس المفتوح Span و Tracer على التوالي. وذلك لأن أجزاء من واجهة برمجة تطبيقات تتبع OpenTelemetry يتم دمجها مباشرة في وقت التشغيل .NET. لمعرفة المزيد، راجع مقدمة إلى OpenTelemetry .NET Tracing API.
// 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();
يمكنك استخدام opentelemetry-api للحصول على معرف التتبع أو معرف النطاق.
إضافة opentelemetry-api-1.0.0.jar (أو أحدث) إلى التطبيق الخاص بك:
// 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;
الحصول على معرف تتبع الطلب ومعرف النطاق في رمزك:
# 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
إنه معيار مفتوح المصدر جديد لقابلية الملاحظة. تعرف على المزيد في OpenTelemetry.
لماذا تستثمر Microsoft Azure Monitor في OpenTelemetry؟
Microsoft هي من بين أكبر المساهمين في القياس المفتوح.
تتمثل اقتراحات القيم الرئيسية لـ OpenTelemetry في أنها محايدة من قبل المورد وتوفر واجهات برمجة تطبيقات/SDK ثابتة عبر اللغات.
مع مرور الوقت، نعتقد أن OpenTelemetry سيمكن عملاء Azure Monitor من مراقبة التطبيقات المكتوبة بلغات تتجاوز لغاتنا المدعومة. كما أنه يوسع أنواع البيانات التي يمكنك جمعها من خلال مجموعة غنية من مكتبات الأجهزة. علاوة على ذلك، تميل مجموعات تطوير البرامج الخاصة ب OpenTelemetry إلى أن تكون أكثر أداء على نطاق واسع من أسلافها، وهي Application Insights SDKs.
يمكنك التفكير في الأمر على أنه برنامج تضمين رفيع يجمع معا جميع مكونات OpenTelemetry للحصول على تجربة من الدرجة الأولى على Azure. يسمى هذا التضمين أيضا التوزيع في OpenTelemetry.
لماذا يجب استخدام "Azure Monitor OpenTelemetry Distro"؟
هناك العديد من المزايا لاستخدام Azure Monitor OpenTelemetry Distro على OpenTelemetry الأصلي من المجتمع:
تقليل جهد التمكين
مدعوم من قبل Microsoft
يجلب ميزات خاصة ب Azure مثل:
أخذ العينات المتوافق مع Application Insights SDKs الكلاسيكي
بروح OpenTelemetry، صممنا توزيعة لتكون مفتوحة وقابلة للتوسعة. على سبيل المثال، يمكنك إضافة:
مصدر بروتوكول القياس المفتوح (OTLP) وإرساله إلى وجهة ثانية في وقت واحد
مكتبات الأجهزة الأخرى غير المضمنة في توزيعة الأجهزة
نظرا لأن Distro يوفر توزيع OpenTelemetry، يدعم Distro أي شيء يدعمه OpenTelemetry. على سبيل المثال، يمكنك إضافة المزيد من معالجات بيانات تتبع الاستخدام أو المصدرين أو مكتبات الأجهزة، إذا كان OpenTelemetry يدعمها.
إشعار
يقوم Distro بتعيين العينة إلى عينة مخصصة ذات معدل ثابت ل Application Insights. يمكنك تغيير هذا إلى عينة مختلفة، ولكن القيام بذلك قد يعطل بعض القدرات المضمنة في Distro.
لمزيد من المعلومات حول أداة أخذ العينات المدعومة، راجع قسم تمكين أخذ العينات في تكوين القياس المفتوح ل Azure Monitor.
بالنسبة للغات التي لا تحتوي على مصدر OpenTelemetry مستقل معتمد، فإن Azure Monitor OpenTelemetry Distro هو الطريقة الوحيدة المدعومة حاليا لاستخدام OpenTelemetry مع Azure Monitor. بالنسبة للغات التي لديها مصدر OpenTelemetry مستقل معتمد، لديك خيار استخدام إما Azure Monitor OpenTelemetry Distro أو مصدر OpenTelemetry المستقل المناسب اعتمادا على سيناريو القياس عن بعد. لمزيد من المعلومات، راجع متى يجب استخدام مصدر Azure Monitor OpenTelemetry؟.
كيف يمكنني اختبار Azure Monitor OpenTelemetry Distro؟
يؤدي اعتماد OpenTelemetry الآن إلى منع الاضطرار إلى الترحيل في وقت لاحق.
متى يجب استخدام مصدر Azure Monitor OpenTelemetry؟
بالنسبة إلى ASP.NET Core وJava Node.js وPython، نوصي باستخدام Azure Monitor OpenTelemetry Distro. إنه سطر واحد من التعليمات البرمجية للبدء.
بالنسبة لجميع سيناريوهات .NET الأخرى، بما في ذلك ASP.NET الكلاسيكية وتطبيقات وحدة التحكم وما إلى ذلك، نوصي باستخدام مصدر .NET Azure Monitor OpenTelemetry: Azure.Monitor.OpenTelemetry.Exporter.
بالنسبة لسيناريوهات بيانات تتبع الاستخدام Python الأكثر تعقيدا التي تتطلب تكوينا متقدما، نوصي باستخدام مصدر بيانات تتبع الاستخدام المفتوح ل Python Azure Monitor.
ما هي حالة الإصدار الحالية للميزات داخل Azure Monitor OpenTelemetry Distro؟
يقسم المخطط التالي دعم ميزة OpenTelemetry لكل لغة.
نعم، لكننا لا نوصي به ولا يدعمه Azure. تم تحسين OpenTelemetry JavaScript بشكل كبير Node.js. بدلا من ذلك، نوصي باستخدام Application Insights JavaScript SDK.
متى يمكننا توقع توفر OpenTelemetry SDK للاستخدام في مستعرضات الويب؟
لا يحتوي OpenTelemetry web SDK على مخطط زمني محدد للتوفر. من المحتمل أن نكون على بعد عدة سنوات من متصفح SDK الذي يعد بديلا قابلا للتطبيق Insights JavaScript SDK.
هل يمكنني اختبار OpenTelemetry في مستعرض ويب اليوم؟
تعد بيئة الاختبار المعزولة للويب OpenTelemetry نسخة المستودع المصممة لجعل OpenTelemetry تعمل في مستعرض. لا يمكن بعد إرسال بيانات تتبع الاستخدام إلى Application Insights. لا تحدد SDK أحداث العميل العامة.
هل يتم دعم تشغيل Application Insights جنبا إلى جنب مع وكلاء منافسين مثل AppDynamics وDataDog و NewRelic؟
لا. هذه الممارسة ليست شيئا نخطط لاختباره أو دعمه، على الرغم من أن Distros الخاصة بنا تسمح لك بالتصدير إلى نقطة نهاية OTLP جنبا إلى جنب مع Azure Monitor في وقت واحد.
هل يمكنني استخدام ميزات المعاينة في بيئات الإنتاج؟
يستخدم بعض العملاء OpenTelemetry Collector كبديل للعامل، على الرغم من أن Microsoft لا تدعم رسميا نهجا يستند إلى عامل لمراقبة التطبيق حتى الآن. في هذه الأثناء، ساهم مجتمع المصدر المفتوح بمصدر OpenTelemetry Collector Azure Monitor الذي يستخدمه بعض العملاء لإرسال البيانات إلى Azure Monitor Application Insights. هذا غير معتمد من قبل Microsoft.
ما الفرق بين OpenCensus وOpenTelemetry؟
OpenCensus هو مقدمة OpenTelemetry. ساعدت Microsoft في الجمع بين OpenTracing وOpenCensus لإنشاء OpenTelemetry، وهو معيار واحد للمراقبة للعالم. تستند Python SDK الحالية الموصى بها للإنتاج ل Azure Monitor إلى OpenCensus. تلتزم Microsoft بإجراء Azure Monitor استنادا إلى OpenTelemetry.