يوفر هذا الدليل إرشادات حول دمج وتخصيص أجهزة OpenTelemetry (OTel) داخل Azure Monitor Application Insights.
لمعرفة المزيد حول مفاهيم OpenTelemetry، راجع نظرة عامة على OpenTelemetry أو الأسئلة المتداولة حول OpenTelemetry.
جمع البيانات تلقائيا
تجمع توزيعات البيانات تلقائيا عن طريق تجميع مكتبات الأجهزة OpenTelemetry.
مكتبات الأجهزة المضمنة
الطلبات
التبعيات
تسجيل
لتقليل أو زيادة عدد السجلات المرسلة إلى Azure Monitor، قم بتكوين التسجيل لتعيين مستوى السجل المناسب أو تطبيق عوامل التصفية. على سبيل المثال، يمكنك اختيار الإرسال فقط Warning والسجلات Error إلى OpenTelemetry/Azure Monitor. لا يتحكم OpenTelemetry في توجيه السجل أو تصفيته - يتخذ التكوين الخاص بك ILogger هذه القرارات. لمزيد من المعلومات حول تكوين ILogger، راجع تكوين التسجيل.
لمزيد من المعلومات حول ILogger، راجع تسجيل الدخول إلى C# و.NETوأمثلة التعليمات البرمجية.
لا يتضمن مصدر Azure Monitor أي مكتبات أجهزة.
يمكنك جمع التبعيات من مجموعات تطوير برامج Azure (SDKs) باستخدام نموذج التعليمات البرمجية التالي للاشتراك يدويا في المصدر.
// 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();
لتقليل أو زيادة عدد السجلات المرسلة إلى Azure Monitor، قم بتكوين التسجيل لتعيين مستوى السجل المناسب أو تطبيق عوامل التصفية. على سبيل المثال، يمكنك اختيار الإرسال فقط Warning والسجلات Error إلى OpenTelemetry/Azure Monitor. لا يتحكم OpenTelemetry في توجيه السجل أو تصفيته - يتخذ التكوين الخاص بك ILogger هذه القرارات. لمزيد من المعلومات حول تكوين ILogger، راجع تكوين التسجيل.
الطلبات
- مستهلكو خدمة رسائل Java (JMS)
- مستهلكو Kafka
- Netty
- مرو
- RabbitMQ
- Servlets
- جدولة Spring
إشعار
يغطي Servlet وNetty autoinstrumentation معظم خدمات Java HTTP، بما في ذلك Java EE وJa jakarta EE وSpring Boot و Quarkus و Micronaut.
التبعيات (بالإضافة إلى نشر التتبع الموزع في المراحل النهائية)
- أباتشي HttpClient
- أباتشي HttpAsyncClient
- AsyncHttpClient
- جوجل HttpClient
- gRPC
- java.net.HttpURLConnection
- جافا 11 HttpClient
- عميل JAX-RS
- رصيف المراكب الصغيرة HttpClient
- JMS
- كافكا
- عميل Netty
- OkHttp
- RabbitMQ
التبعيات (بدون نشر التتبع الموزع في المراحل النهائية)
- يدعم Cassandra
- يدعم اتصال قاعدة بيانات Java (JDBC)
- يدعم MongoDB (غير متزامن ومزامنته)
- يدعم Redis (Lettuce وJedis)
المقاييس
- مقاييس Micrometer، بما في ذلك مقاييس Spring Boot Actuator
- مقاييس ملحقات إدارة Java (JMX)
سجلات
- Logback (بما في ذلك خصائص MDC) ¹
- Log4j (بما في ذلك خصائص سياق MDC/مؤشر الترابط) ¹
- تسجيل JBoss (بما في ذلك خصائص MDC) ¹
- java.util.logging ¹
لتقليل أو زيادة عدد السجلات التي يجمعها Azure Monitor، قم أولا بتعيين مستوى التسجيل المطلوب (مثل WARNING أو ERROR) في مكتبة تسجيل التطبيق.
المجموعة الافتراضية
يتم جمع بيانات تتبع الاستخدام المنبعثة من Azure SDKs التالية تلقائيا بشكل افتراضي:
[//]: # "Azure Cosmos DB 4.22.0+ due to https://github.com/Azure/azure-sdk-for-java/pull/25571"
[//]: # "the remaining above names and links scraped from https://azure.github.io/azure-sdk/releases/latest/java.html"
[//]: # "and version synched manually against the oldest version in maven central built on azure-core 1.14.0"
[//]: # ""
[//]: # "var table = document.querySelector('#tg-sb-content > div > table')"
[//]: # "var str = ''"
[//]: # "for (var i = 1, row; row = table.rows[i]; i++) {"
[//]: # " var name = row.cells[0].getElementsByTagName('div')[0].textContent.trim()"
[//]: # " var stableRow = row.cells[1]"
[//]: # " var versionBadge = stableRow.querySelector('.badge')"
[//]: # " if (!versionBadge) {"
[//]: # " continue"
[//]: # " }"
[//]: # " var version = versionBadge.textContent.trim()"
[//]: # " var link = stableRow.querySelectorAll('a')[2].href"
[//]: # " str += '* [' + name + '](' + link + ') ' + version + '\n'"
[//]: # "}"
[//]: # "console.log(str)"
طلبات تطبيقات Spring Boot الأصلية
- شبكة الربيع
- Spring Web MVC (الموديل-View-Controller)
- الربيع WebFlux
تبعيات لتطبيقات Spring Boot الأصلية
المقاييس
سجلات لتطبيقات Spring Boot الأصلية
لتقليل أو زيادة عدد السجلات التي يجمعها Azure Monitor، قم أولا بتعيين مستوى التسجيل المطلوب (مثل WARNING أو ERROR) في مكتبة تسجيل التطبيق.
بالنسبة لتطبيقات Quartz الأصلية، انظر إلى وثائق Quarkus.
إشعار
يدعم مجتمع Quarkus امتدادات Quarkus ويحافظ عليها. للحصول على المساعدة، استخدم قنوات دعم مجتمع Quarkus. لا توفر Microsoft الدعم الفني لهذا التكامل.
يتم تضمين مكتبات OpenTelemetry Instrumentation التالية كجزء من Azure Monitor Application Insights Distro. لمزيد من المعلومات، راجع Azure SDK ل JavaScript.
الطلبات
التبعيات
سجلات
لتقليل أو زيادة عدد السجلات التي يجمعها Azure Monitor، قم أولا بتعيين مستوى التسجيل المطلوب (مثل WARNING أو ERROR) في مكتبة تسجيل التطبيق.
يمكن تكوين الأجهزة باستخدام AzureMonitorOpenTelemetryOptions:
export class BunyanInstrumentationSample {
static async run() {
// Dynamically import Azure Monitor and Bunyan
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const bunyanMod = await import("bunyan");
const bunyan = (bunyanMod as any).default ?? bunyanMod;
// Enable Azure Monitor integration and bunyan instrumentation
const options = {
instrumentationOptions: {
bunyan: { enabled: true },
},
};
const monitor = useAzureMonitor(options);
// Emit a test log entry
const log = (bunyan as any).createLogger({ name: "testApp" });
log.info(
{
testAttribute1: "testValue1",
testAttribute2: "testValue2",
testAttribute3: "testValue3",
},
"testEvent"
);
console.log("Bunyan log emitted");
}
}
الطلبات
التبعيات
سجلات
لتقليل أو زيادة عدد السجلات التي يجمعها Azure Monitor، قم أولا بتعيين مستوى التسجيل المطلوب (مثل WARNING أو ERROR) في مكتبة تسجيل التطبيق.
يمكن العثور على أمثلة لاستخدام مكتبة تسجيل Python على GitHub.
يتم جمع بيانات تتبع الاستخدام الصادرة عن مجموعات تطوير برامج Azure (SDKs) تلقائيا بشكل افتراضي.
الحواشي السفليه
- ¹: يدعم الإبلاغ التلقائي عن الاستثناءات غير المعالجة/غير المعالجة
- ²: يدعم مقاييس القياس المفتوح
تلميح
تعتبر جميع مقاييس OpenTelemetry سواء تم جمعها تلقائيا من مكتبات الأجهزة أو التي تم جمعها يدويا من الترميز المخصص حاليا "مقاييس مخصصة" ل Application Insights لأغراض الفوترة.
تعرف على المزيد.
يمكنك جمع المزيد من البيانات تلقائيا عند تضمين مكتبات الأجهزة من مجتمع OpenTelemetry.
تنبيه
نحن لا ندعم أو نضمن جودة مكتبات الأجهزة المجتمعية. اقتراح واحد لنشرنا أو نشره أو التصويت عليه في مجتمع الملاحظات لدينا. كن على علم، يعتمد بعضها على مواصفات OpenTelemetry التجريبية وقد يقدم تغييرات كسرية مستقبلية.
لإضافة مكتبة مجتمع، استخدم ConfigureOpenTelemetryMeterProvider الأسلوبين أو ConfigureOpenTelemetryTracerProvider بعد إضافة حزمة NuGet للمكتبة.
يوضح المثال التالي كيف يمكن إضافة تقرير عن حالة النظام وقت التشغيل لجمع مقاييس إضافية:
dotnet add package OpenTelemetry.Instrumentation.Runtime
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry meter provider to add runtime instrumentation.
builder.Services.ConfigureOpenTelemetryMeterProvider((sp, builder) => builder.AddRuntimeInstrumentation());
// Add the Azure Monitor telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
يوضح المثال التالي كيف يمكن إضافة تقرير عن حالة النظام وقت التشغيل لجمع مقاييس إضافية:
// 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 في الخطوات التالية.
لا يمكنك استخدام مكتبات الأجهزة المجتمعية مع تطبيقات GraalVM Java الأصلية.
export class RegisterExpressInstrumentationSample {
static async run() {
// Dynamically import Azure Monitor and Express instrumentation
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { registerInstrumentations } = await import("@opentelemetry/instrumentation");
const { ExpressInstrumentation } = await import("@opentelemetry/instrumentation-express");
// Initialize Azure Monitor (uses env var if set)
const monitor = useAzureMonitor();
// Register the Express instrumentation
registerInstrumentations({
instrumentations: [new ExpressInstrumentation()],
});
console.log("Express instrumentation registered");
}
}
لإضافة مكتبة أجهزة المجتمع (غير مدعومة/مضمنة رسميا في توزيعة Azure Monitor)، يمكنك استخدام الأجهزة مباشرة. يمكن العثور على قائمة مكتبات الأجهزة المجتمعية هنا.
إشعار
لا يوصى باستخدام مكتبة الأجهزة المدعومة يدويا باستخدام instrument() و distro 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())
كاشفات الموارد
تكتشف كاشفات الموارد بيانات تعريف البيئة عند بدء التشغيل وتملأ سمات مورد OpenTelemetry مثل service.name، cloud.providerو و cloud.resource_id. تعمل بيانات التعريف هذه على تعزيز التجارب في Application Insights مثل Application Map وربط الحوسبة، كما أنها تعمل على تحسين الارتباط عبر التتبعات والمقاييس والسجلات.
تلميح
تصف سمات الموارد العملية وبيئتها. تصف سمات Span عملية واحدة. استخدام سمات الموارد للخصائص على مستوى التطبيق مثل service.name.
البيئات المدعومة
| وسط |
آلية عمل الاكتشاف |
Notes |
| "Azure App Service" |
تقرأ اللغة SDK أو توزيعة Azure Monitor متغيرات بيئة App Service المعروفة وبيانات تعريف المضيف |
يعمل مع .NET وJava وNode.jsوPython عند استخدام الإرشادات الواردة في هذه المقالة. |
| Azure Functions |
راجع كيفية Azure Functions OpenTelemetry |
توجد جميع إرشادات Azure Functions هناك. |
| أجهزة Azure الظاهرية |
تستعلم SDK أو التوزيعة للغة عن خدمة بيانات تعريف مثيل Azure |
تأكد من أن الجهاز الظاهري لديه حق الوصول إلى نقطة نهاية خدمة بيانات تعريف المثيل. |
| خدمة Azure Kubernetes (AKS) |
استخدام معالج OpenTelemetry Collector k8sattributes لإضافة بيانات تعريف Kubernetes |
موصى به لجميع اللغات التي تعمل بتنسيق AKS. |
| Azure Container Apps |
تقوم أجهزة الكشف بتعيين متغيرات البيئة ومعرفات الموارد عند توفرها |
يمكنك أيضا الضبط OTEL_RESOURCE_ATTRIBUTES لملء الفجوات. |
الأجهزة اليدوية والآلية
تتيح الأجهزة التلقائية وتوزيعات Azure Monitor اكتشاف الموارد عند التشغيل في بيئات Azure حيث يتم دعمها.
بالنسبة للإعدادات اليدوية، يمكنك تعيين سمات الموارد مباشرة باستخدام خيارات OpenTelemetry القياسية:
# Applies to .NET (ASP.NET/ASP.NET Core), Java, Node.js, and Python
export OTEL_SERVICE_NAME="my-service"
export OTEL_RESOURCE_ATTRIBUTES="cloud.provider=azure,cloud.region=westus,cloud.resource_id=/subscriptions/<SUB>/resourceGroups/<RG>/providers/Microsoft.Web/sites/<APP>"
على Windows PowerShell:
$Env:OTEL_SERVICE_NAME="my-service"
$Env:OTEL_RESOURCE_ATTRIBUTES="cloud.provider=azure,cloud.region=westus,cloud.resource_id=/subscriptions/<SUB>/resourceGroups/<RG>/providers/Microsoft.Web/sites/<APP>"
اعتبارات استيعاب OTLP
- يستخدم
service.name Application Insights لاشتقاق اسم دور السحابة. اختر اسما ثابتا لكل خدمة لتجنب العقد المجزأة في مخطط التطبيق.
-
cloud.resource_id يحسن ارتباط الحوسبة بموارد Azure. إذا كانت هذه السمة مفقودة، فقد لا تظهر بعض التجارب مورد Azure الذي أنتج البيانات.
جمع بيانات تتبع الاستخدام المخصصة
يشرح هذا القسم كيفية جمع بيانات تتبع الاستخدام المخصصة من التطبيق الخاص بك.
اعتمادا على اللغة ونوع الإشارة، هناك طرق مختلفة لجمع بيانات تتبع الاستخدام المخصصة، بما في ذلك:
- واجهة برمجة تطبيقات OpenTelemetry
- مكتبات التسجيل/المقاييس الخاصة باللغة
- واجهة برمجة تطبيقات Application Insights الكلاسيكية
يمثل الجدول التالي أنواع بيانات تتبع الاستخدام المخصصة المدعومة حاليا:
| اللغة |
أحداث مخصصة |
مقاييس مخصصة |
التبعيات |
استثناءات |
طرق عرض الصفحة |
الطلبات |
اثار |
|
ASP.NET الأساسية |
|
|
|
|
|
|
|
| واجهة برمجة تطبيقات OpenTelemetry |
|
نعم |
نعم |
نعم |
|
نعم |
|
ILogger واجهة برمجة التطبيقات |
|
|
|
|
|
|
نعم |
| واجهة برمجة تطبيقات الذكاء الاصطناعي الكلاسيكية |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
جاوة |
|
|
|
|
|
|
|
| واجهة برمجة تطبيقات OpenTelemetry |
|
نعم |
نعم |
نعم |
|
نعم |
|
Logback, , Log4jJUL |
|
|
|
نعم |
|
|
نعم |
| قياسات ميكرومتر |
|
نعم |
|
|
|
|
|
| واجهة برمجة تطبيقات الذكاء الاصطناعي الكلاسيكية |
نعم |
نعم |
نعم |
نعم |
نعم |
نعم |
نعم |
|
|
|
|
|
|
|
|
|
Node.js |
|
|
|
|
|
|
|
| واجهة برمجة تطبيقات OpenTelemetry |
|
نعم |
نعم |
نعم |
|
نعم |
|
|
|
|
|
|
|
|
|
|
بايثون |
|
|
|
|
|
|
|
| واجهة برمجة تطبيقات OpenTelemetry |
|
نعم |
نعم |
نعم |
|
نعم |
|
| وحدة تسجيل Python |
|
|
|
|
|
|
نعم |
| ملحق الأحداث |
نعم |
|
|
|
|
|
نعم |
إشعار
يجمع Application Insights Java 3.x وApplication Insights Node.js 3.x بيانات تتبع الاستخدام من واجهة برمجة تطبيقات Application Insights الكلاسيكية. يبسط هذا السلوك الترقيات ويدعم مؤقتا بيانات تتبع الاستخدام المخصصة حتى تتضمن واجهة برمجة تطبيقات القياس المفتوح جميع أنواع بيانات تتبع الاستخدام المخصصة.
إضافة القياسات المخصصة
في هذا السياق، يشير مصطلح المقاييس المخصصة إلى أدوات التعليمات البرمجية يدويا لجمع مقاييس إضافية تتجاوز ما تجمعه مكتبات أدوات القياس المفتوح تلقائيا. لمعرفة المزيد حول استخدام المقاييس، راجع المقاييس في Application Insights.
تقدم OpenTelemetry API ست "أدوات" قياسية لتغطية سيناريوهات القياس المختلفة وتحتاج إلى اختيار "نوع التجميع" الصحيح عند تصور المقاييس في Metrics Explorer. هذا المطلب صحيح عند استخدام OpenTelemetry Metric API لإرسال المقاييس وعند استخدام مكتبة الأجهزة.
يعرض الجدول التالي أنواع التجميع الموصى بها لكل من أدوات القياس OpenTelemetry.
| أداة القياس عن بعد المفتوحة |
نوع تجميع Azure Monitor |
| العداد |
المجموع |
| عداد غير متزامن |
المجموع |
| المدرج التكراري |
الحد الأدنى والحد الأقصى والمتوسط والمجموع والعدد |
| مقياس غير متزامن |
المتوسط |
| UpDownCounter |
المجموع |
| UpDownCounter غير متزامن |
المجموع |
تنبيه
أنواع التجميع الأخرى ليست ذات معنى في معظم الحالات.
تصف مواصفات 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);
}
}
إدخال OpenTelemetry:
إنشاء مدرج تكراري:
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);
إشعار
يدعم مجتمع Quarkus امتدادات Quarkus ويحافظ عليها. للحصول على المساعدة، استخدم قنوات دعم مجتمع Quarkus. لا توفر Microsoft الدعم الفني لهذا التكامل.
export class HistogramSample {
static async run() {
// Dynamically import Azure Monitor and metrics API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a histogram and record values
const meter = metrics.getMeter("testMeter");
const histogram = meter.createHistogram("histogram");
histogram.record(1, { testKey: "testValue" });
histogram.record(30, { testKey: "testValue2" });
histogram.record(100, { testKey2: "testValue" });
console.log("Histogram metrics recorded");
}
}
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
import os
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_histogram_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_histogram_demo")
# Record three values to the histogram.
histogram = meter.create_histogram("histogram")
histogram.record(1.0, {"test_key": "test_value"})
histogram.record(100.0, {"test_key2": "test_value"})
histogram.record(30.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
مثال العداد
يجب أن يشترك بدء تشغيل التطبيق في مقياس حسب الاسم:
// 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"));
}
}
إدخال OpenTelemetry:
إنشاء العداد:
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
LongCounter myFruitCounter = meter.counterBuilder("MyFruitCounter")
.build();
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "green"));
myFruitCounter.add(5, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(4, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
إشعار
يدعم مجتمع Quarkus امتدادات Quarkus ويحافظ عليها. للحصول على المساعدة، استخدم قنوات دعم مجتمع Quarkus. لا توفر Microsoft الدعم الفني لهذا التكامل.
export class CounterSample {
static async run() {
// Dynamically import Azure Monitor and metrics API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a counter and add some sample values
const meter = metrics.getMeter("otel_azure_monitor_counter_demo");
const counter = meter.createCounter("MyFruitCounter");
counter.add(1, { name: "apple", color: "red" });
counter.add(2, { name: "lemon", color: "yellow" });
counter.add(1, { name: "lemon", color: "yellow" });
counter.add(2, { name: "apple", color: "green" });
counter.add(5, { name: "apple", color: "red" });
counter.add(4, { name: "lemon", color: "yellow" });
console.log("Counter metrics recorded");
}
}
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
import os
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_counter_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_counter_demo")
# Create a counter metric with the name "counter".
counter = meter.create_counter("counter")
# Add three values to the counter.
# The first argument to the `add()` method is the value to add.
# The second argument is a dictionary of dimensions.
# Dimensions are used to group related metrics together.
counter.add(1.0, {"test_key": "test_value"})
counter.add(5.0, {"test_key2": "test_value"})
counter.add(3.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
مثال على القياس
يجب أن يشترك بدء تشغيل التطبيق في مقياس حسب الاسم:
// 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"));
});
}
}
إدخال OpenTelemetry:
إنشاء مقياس:
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
meter.gaugeBuilder("gauge")
.buildWithCallback(
observableMeasurement -> {
double randomNumber = Math.floor(Math.random() * 100);
observableMeasurement.record(randomNumber, Attributes.of(AttributeKey.stringKey("testKey"), "testValue"));
});
إشعار
يدعم مجتمع Quarkus امتدادات Quarkus ويحافظ عليها. للحصول على المساعدة، استخدم قنوات دعم مجتمع Quarkus. لا توفر Microsoft الدعم الفني لهذا التكامل.
export class GaugeSample {
static async run() {
// Dynamically import Azure Monitor and metrics API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { metrics } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create an observable gauge and register a callback
const meter = metrics.getMeter("testMeter");
const gauge = meter.createObservableGauge("gauge");
gauge.addCallback((observableResult) => {
const randomNumber = Math.floor(Math.random() * 100);
observableResult.observe(randomNumber, { testKey: "testValue" });
});
console.log("Observable gauge registered");
}
}
# Import the necessary packages.
from typing import Iterable
import os
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
from opentelemetry.metrics import CallbackOptions, Observation
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_gauge_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_gauge_demo")
# Define two observable gauge generators.
# The first generator yields a single observation with the value 9.
# The second generator yields a sequence of 10 observations with the value 9 and a different dimension value for each observation.
def observable_gauge_generator(options: CallbackOptions) -> Iterable[Observation]:
yield Observation(9, {"test_key": "test_value"})
def observable_gauge_sequence(options: CallbackOptions) -> Iterable[Observation]:
observations = []
for i in range(10):
observations.append(
Observation(9, {"test_key": i})
)
return observations
# Create two observable gauges using the defined generators.
gauge = meter.create_observable_gauge("gauge", [observable_gauge_generator])
gauge2 = meter.create_observable_gauge("gauge2", [observable_gauge_sequence])
# Wait for background execution.
input()
إضافة استثناءات مخصصة
حدد مكتبات الأجهزة التي تقوم تلقائيا بالإبلاغ عن الاستثناءات إلى 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 (أو أحدث) إلى التطبيق الخاص بك:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
تعيين الحالة إلى error وتسجيل استثناء في التعليمات البرمجية الخاصة بك:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
تعيين الحالة إلى error وتسجيل استثناء في التعليمات البرمجية الخاصة بك:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
تقوم Node.js SDK بتصدير الاستثناءات المستندة إلى الامتداد المسجلة يدويا إلى Application Insights كاستثناءات فقط عند تسجيلها على نطاق المستوى الأعلى أو تابع لنص بعيد أو داخلي.
export class CustomExceptionSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a span and record an exception
const tracer = trace.getTracer("testTracer");
const span = tracer.startSpan("hello");
try {
throw new Error("Test Error");
} catch (error) {
span.recordException(error as Error);
} finally {
span.end();
}
console.log("Exception recorded on span");
}
}
يتم تنفيذ 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، ولكن يمكنك توفير أي .ActivityKind
ActivityKind.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، ولكن يمكنك توفير أي .ActivityKind
ActivityKind.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 (أو أحدث) إلى التطبيق الخاص بك:
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-annotations</artifactId>
<version>1.32.0</version>
</dependency>
استخدم @WithSpanالتعليق التوضيحي لإرسال مدى في كل مرة يتم فيها تنفيذ طريقتك:
import io.opentelemetry.instrumentation.annotations.WithSpan;
@WithSpan(value = "your span name")
public void yourMethod() {
}
بشكل افتراضي، ينتهي النطاق في dependencies الجدول بنوع InProcالتبعية .
بالنسبة للأساليب التي تمثل مهمة خلفية لم يتم التقاطها بواسطة البنية التلقائية، نوصي بتطبيق السمة kind = SpanKind.SERVER على @WithSpan التعليق التوضيحي للتأكد من ظهورها في جدول Application Insights requests .
استخدام OpenTelemetry API
إذا لم يفي التعليق التوضيحي السابق ل OpenTelemetry @WithSpan باحتياجاتك، يمكنك إضافة الامتدادات باستخدام واجهة برمجة تطبيقات OpenTelemetry.
إضافة opentelemetry-api-1.0.0.jar (أو أحدث) إلى التطبيق الخاص بك:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
GlobalOpenTelemetry استخدم الفئة لإنشاء Tracer:
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();
}
إدخال OpenTelemetry:
Tracerإنشاء :
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = openTelemetry.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();
}
إشعار
يدعم مجتمع Quarkus امتدادات Quarkus ويحافظ عليها. للحصول على المساعدة، استخدم قنوات دعم مجتمع Quarkus. لا توفر Microsoft الدعم الفني لهذا التكامل.
export class CustomTraceSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor({
azureMonitorExporterOptions: {
connectionString:
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "<your-connection-string>",
},
});
// Create a custom span, add attributes/events, then end
const tracer = trace.getTracer("otel_azure_monitor_custom_trace_demo");
const span = tracer.startSpan("doWork");
try {
span.setAttribute("component", "worker");
span.setAttribute("operation.id", "42");
span.addEvent("invoking doWork");
for (let i = 0; i < 1_000_000; i++) { /* simulate work */ }
} catch (err) {
span.recordException(err as Error);
} finally {
span.end();
}
console.log("Custom span recorded");
}
}
يمكن استخدام 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 الأحداث المخصصة في customEvents الجدول. تتمثل إحدى طرق تحليلها وتصفيتها وتصورها في استخدام تجارب استخدام Application Insights.
إذا كنت ترغب في أتمتة مجموعة أحداث التفاعل من جانب العميل، يمكنك استخدام المكون الإضافي في JavaScript SDK.
الأحداث المخصصة في المعاينة العامة وتستخدم Azure.Monitor.OpenTelemetry.AspNetCore 1.3.0-beta.3.
لإرسال CustomEvent باستخدام ILogger، قم بتعيين السمة "microsoft.custom_event.name" في قالب الرسالة.
// Create a logger factory and configure OpenTelemetry with Azure Monitor
var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter();
});
});
// Create a logger for the specified category
var logger = loggerFactory.CreateLogger(logCategoryName);
// Log a custom event with a custom name and additional attribute
// The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}", "test-event-name", "val1");
الأحداث المخصصة في المعاينة العامة وتستخدم Azure.Monitor.OpenTelemetry.Exporter 1.4.0-beta.3.
لإرسال CustomEvent باستخدام ILogger، قم بتعيين السمة "microsoft.custom_event.name" في قالب الرسالة.
// Create a logger factory and configure OpenTelemetry with Azure Monitor
var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter();
});
});
// Create a logger for the specified category
var logger = loggerFactory.CreateLogger(logCategoryName);
// Log a custom event with a custom name and additional attribute
// The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.LogInformation("{microsoft.custom_event.name} {additional_attrs}", "test-event-name", "val1");
لإرسال customEvent مع عامل Java، قم بتعيين السمة "microsoft.custom_event.name" على سجل OpenTelemetry.
اعتمادا على ما إذا كان وكيل java ل application insights قيد الاستخدام، أو SDK للتكوين التلقائي، تختلف طريقة إحضار مسجل OpenTelemetry قليلا. يتم شرح هذه التفاصيل بشكل أكبر في الأمثلة التالية.
بالنسبة لعامل java ل application insights:
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.logs.Logger;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.logs.Severity;
Logger logger = GlobalOpenTelemetry.get().getLogsBridge().get("opentelemetry-logger");
logger.logRecordBuilder()
.setAttribute(AttributeKey.stringKey("microsoft.custom_event.name"),"test-event-name")
.setSeverity(Severity.INFO)
.emit();
لتكوين SDK تلقائيا:
import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigure;
import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigureOptions;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.logs.Logger;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder;
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
AzureMonitorAutoConfigureOptions options = new AzureMonitorAutoConfigureOptions();
options.connectionString("<your connection string>");
AzureMonitorAutoConfigure.customize(sdkBuilder, options);
OpenTelemetry openTelemetry = sdkBuilder.build().getOpenTelemetrySdk();
Logger logger = openTelemetry.getLogsBridge().get("opentelemetry-logger");
logger.logRecordBuilder()
.setAttribute(AttributeKey.stringKey("microsoft.custom_event.name"),"test-event-name")
.setSeverity(Severity.INFO)
.emit();
لإصدار أحداث مخصصة بشكل موثوق، استخدم واجهة برمجة تطبيقات القياس المفتوح مباشرة. لا تدعم بعض أطر عمل التسجيل إلحاق سمة الأحداث المخصصة أو تحليلها.
لا يمكن إرسال customEvent باستخدام السمة "microsoft.custom_event.name" في Java الأصلي.
لإرسال customEvent باستخدام logger.emit، قم بتعيين السمة "microsoft.custom_event.name" في كائن السجل attributes . يمكن أيضا تضمين سمات أخرى حسب الحاجة.
export class CustomEventSample {
static async run() {
// Dynamically import Azure Monitor and the OpenTelemetry logs API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { logs, SeverityNumber } = await import("@opentelemetry/api-logs");
// Initialize Azure Monitor (enables logs bridge)
const monitor = useAzureMonitor();
// Get a logger and emit a customEvent by setting the microsoft attribute key
const logger = logs.getLogger("my-app-logger");
logger.emit({
body: "Hello World!",
severityNumber: SeverityNumber.INFO,
attributes: {
"microsoft.custom_event.name": "test-event-name",
"additional_attrs": "val1",
},
});
// Example: populate client_IP via attribute 'client.address'
logger.emit({
body: "This entry will have a custom client_IP",
severityNumber: SeverityNumber.INFO,
attributes: {
"microsoft.custom_event.name": "test_event",
"client.address": "192.168.1.1",
},
});
console.log("Custom events emitted");
}
}
لإرسال customEvent في Python، استخدم مكتبة التسجيل مع السمة "microsoft.custom_event.name" في المعلمة extra .
import logging
from azure.monitor.opentelemetry import configure_azure_monitor
# Set up your application logger
logger = logging.getLogger("my-app-logger")
# Configure Azure Monitor to collect logs from the specified logger name
configure_azure_monitor(
logger_name="my-app-logger", # Collect logs from your namespaced logger
)
# Log a custom event with a custom name and additional attribute
# The 'microsoft.custom_event.name' value will be used as the name of the customEvent
logger.warning(
"Hello World!",
extra={
"microsoft.custom_event.name": "test-event-name",
"additional_attrs": "val1"
}
)
# You can also populate fields like client_IP with attribute `client.address`
logger.info(
"This entry will have a custom client_IP",
extra={
"microsoft.custom_event.name": "test_event",
"client.address": "192.168.1.1"
}
)
تعديل القياس عن بُعد
يشرح هذا القسم كيفية تعديل بيانات تتبع الاستخدام.
إضافة سمات النطاق
يمكن أن تتضمن هذه السمات إضافة خاصية مخصص إلى قياسك عن بُعد. يمكنك أيضًا استخدام سمات لتعيين الحقول الاختيارية في مخطط Application Insights، مثل IP العميل.
إضافة خاصية مخصصة إلى Span
يتم تصدير أي سمات تضيفها إلى الامتدادات كخصائص مخصصة. يقومون بتعبئة حقل customDimensions في جدول الطلبات أو التبعيات أو التتبعات أو الاستثناءات.
لإضافة سمات النطاق، استخدم أي من الطريقتين التاليتين:
تلميح
تتمثل ميزة استخدام الخيارات التي توفرها مكتبات الأجهزة، عندما تكون متاحة، في أن السياق بأكمله متاح. ونتيجة لذلك، يمكن للمستخدمين تحديد لإضافة المزيد من السمات أو تصفيتها. على سبيل المثال، يتيح خيار الإثراء في مكتبة الأجهزة HttpClient للمستخدمين الوصول إلى HttpRequestMessageوHttpResponseMessage نفسه. يمكنهم تحديد أي شيء منه وتخزينه كسمة.
توفر العديد من مكتبات الأجهزة خيارا تثري. للحصول على إرشادات، راجع ملفات readme لمكتبات الأجهزة الفردية:
استخدم معالج مخصص:
تلميح
أضف المعالج الموضح هنا قبل إضافة 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();
أضف 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 لمكتبات الأجهزة الفردية:
استخدم معالج مخصص:
تلميح
أضف المعالج الموضح هنا قبل مصدر 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();
أضف 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 (أو أحدث) إلى التطبيق الخاص بك:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
إضافة أبعاد مخصصة في رمزك:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
إضافة أبعاد مخصصة في رمزك:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
export class SpanAttributeEnrichmentSample {
static async run() {
// Dynamically import the Azure Monitor integration
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
// Create a SpanEnrichingProcessor to add custom dimensions
class SpanEnrichingProcessor {
forceFlush() { return Promise.resolve(); }
shutdown() { return Promise.resolve(); }
onStart() {}
onEnd(span: any) {
(span as any).attributes = (span as any).attributes || {};
(span as any).attributes["CustomDimension1"] = "value1";
(span as any).attributes["CustomDimension2"] = "value2";
}
}
// Initialize Azure Monitor with the custom processor
const monitor = useAzureMonitor({
spanProcessors: [new SpanEnrichingProcessor()],
});
console.log("Span enrichment processor registered");
}
}
استخدم معالج مخصص:
...
# 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 للطلبات عن طريق تعيين سمة على النطاق. يستخدم Application Insights عنوان IP لإنشاء سمات موقع المستخدم ثم يتجاهله افتراضيا.
استخدم مثال الخاصية
// 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>");
استخدم مثال الخاصية
// 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 هذا الحقل تلقائيا.
يتم ملء هذا الحقل تلقائيا.
استخدم مثال الخاصية المخصصة، ولكن استبدل الأسطر التالية من التعليمات البرمجية:
export class SetUserIpSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor();
// Framework-agnostic helper to set client IP on the active server span
const setIpForRequest = (clientIp: string) => {
const span = trace.getActiveSpan();
if (span) {
// Preferred attribute for client IP
span.setAttribute("client.address", clientIp);
// Optional: legacy/alternate attribute
span.setAttribute("http.client_ip", clientIp);
}
};
// Call setIpForRequest("<IP Address>") from within your web framework's request pipeline
console.log("Use setIpForRequest('<IP Address>') inside your request handler to stamp the active span.");
}
}
استخدم مثال الخاصية
# 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 للطلبات باستخدام الإرشادات التالية. معرف المستخدم هو معرف مستخدم مجهول. معرف المستخدم المصادق عليه هو معرف مستخدم معروف.
هام
راجع قوانين الخصوصية المعمول بها قبل تعيين معرف المستخدم المصادق عليه.
استخدم مثال الخاصية المخصصة:
// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<User Id>");
استخدم مثال الخاصية المخصصة:
// Add the user ID to the activity as a tag, but only if the activity is not null.
activity?.SetTag("enduser.id", "<User Id>");
قم بتعبئة user ID الحقل في requestsالجدول أو dependenciesأو .exceptions
إضافة opentelemetry-api-1.0.0.jar (أو أحدث) إلى التطبيق الخاص بك:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
عيّن user_Id في التعليمات البرمجية الخاصة بك:
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser"); // (user_AuthenticatedId)
Span.current().setAttribute("enduser.pseudo.id", "myuser"); // (user_Id)
قم بتعبئة user ID الحقل في requestsالجدول أو dependenciesأو .exceptions
عيّن user_Id في التعليمات البرمجية الخاصة بك:
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser"); // (user_AuthenticatedId)
Span.current().setAttribute("enduser.pseudo.id", "myuser"); // (user_Id)
استخدم مثال الخاصية المخصصة، ولكن استبدل الأسطر التالية من التعليمات البرمجية:
export class SetUserIdSample {
static async run() {
// Dynamically import Azure Monitor and tracing API
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const { trace } = await import("@opentelemetry/api");
// Initialize Azure Monitor
const monitor = useAzureMonitor();
// Framework-agnostic helper to set user identifiers on the active server span
const setUserForRequest = (authenticatedId?: string, anonymousId?: string) => {
const span = trace.getActiveSpan();
if (span) {
if (authenticatedId) span.setAttribute("enduser.id", authenticatedId); // user_AuthenticatedId
if (anonymousId) span.setAttribute("enduser.pseudo.id", anonymousId); // user_Id
}
};
// Call setUserForRequest("<authenticated-id>", "<anonymous-id>") inside your request handler
console.log("Use setUserForRequest('<auth-id>', '<anon-id>') inside your request handler to stamp the active span.");
}
}
استخدم مثال الخاصية المخصصة، ولكن استبدل الأسطر التالية من التعليمات البرمجية:
# Set the `enduser.id` attribute of the span to the specified user ID.
span._attributes["enduser.id"] = "<User ID>"
إضافة سمات السجل
يستخدم OpenTelemetry . NET's ILogger.
يمكن إرفاق أبعاد مخصصة بالسجلات باستخدام قالب رسالة.
يستخدم OpenTelemetry . NET's ILogger.
يمكن إرفاق أبعاد مخصصة بالسجلات باستخدام قالب رسالة.
يتم تلقائيا وضع علامة على Logback وLog4j وjava.util.logging. يمكن إرفاق أبعاد مخصصة بسجلاتك بهذه الطرق:
بالنسبة لتطبيقات Spring Boot الأصلية، يتم وضع علامة على Logback خارج الصندوق.
export class BunyanLogAttributesSample {
static async run() {
// Dynamically import Azure Monitor and Bunyan
const { useAzureMonitor } = await import("@azure/monitor-opentelemetry");
const bunyanMod = await import("bunyan");
const bunyan = (bunyanMod as any).default ?? bunyanMod;
// Enable Azure Monitor integration and bunyan instrumentation
const monitor = useAzureMonitor({
instrumentationOptions: { bunyan: { enabled: true } },
});
// Emit a log with custom attributes
const log = (bunyan as any).createLogger({ name: "testApp" });
log.info({ key1: "value1", feature: "demo" }, "Warning log with properties");
console.log("Bunyan log with attributes emitted");
}
}
مكتبة تسجيل Python مفسرة تلقائيا. يمكنك إرفاق أبعاد مخصصة بسجلاتك عن طريق تمرير قاموس إلى وسيطة extra سجلاتك:
...
# Create a warning log message with the properties "key1" and "value1".
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
الحصول على معرف التتبع أو معرف النطاق
يمكنك الحصول على Trace ID و Span ID من النطاق النشط حاليا باستخدام الخطوات التالية.
إشعار
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 (أو أحدث) إلى التطبيق الخاص بك:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
الحصول على معرف تتبع الطلب ومعرف النطاق في رمزك:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
الحصول على معرف تتبع الطلب ومعرف النطاق في رمزك:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
الحصول على معرف تتبع الطلب ومعرف النطاق في رمزك:
export class GetTraceAndSpanIdSample {
static async run() {
// Dynamically import tracing API
const { trace } = await import("@opentelemetry/api");
// Read the span/trace id from the active span (if any)
const activeSpan = trace.getActiveSpan();
const spanId = activeSpan?.spanContext().spanId;
const traceId = activeSpan?.spanContext().traceId;
console.log("SpanId:", spanId, "TraceId:", traceId);
}
}
الحصول على معرف تتبع الطلب ومعرف النطاق في رمزك:
# 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
الخطوات التالية
إشعار
يدعم مجتمع Quarkus امتدادات Quarkus ويحافظ عليها. للحصول على المساعدة، استخدم قنوات دعم مجتمع Quarkus. لا توفر Microsoft الدعم الفني لهذا التكامل.