Este guia fornece instruções sobre como integrar e personalizar a instrumentação do OpenTelemetry (OTel) no Azure Monitor Application Insights.
Para saber mais sobre os conceitos do OpenTelemetry, confira a Visão geral do OpenTelemetry ou as Perguntas frequentes sobre o OpenTelemetry.
Coleta automática de dados
As distribuições coletam dados automaticamente ao integrar as bibliotecas de instrumentação do OpenTelemetry.
Bibliotecas de instrumentação incluídas
Solicitações
Dependências
Registro
Para reduzir ou aumentar o número de logs enviados ao Azure Monitor, configure o log para definir o nível de log apropriado ou aplicar filtros. Por exemplo, você pode optar por enviar somente Warning
e Error
logs para o OpenTelemetry/Azure Monitor. O OpenTelemetry não controla o roteamento ou a filtragem de logs . Sua ILogger
configuração toma essas decisões. Para obter mais informações sobre a configuração ILogger
, veja Configurar registro.
Para obter mais informações sobre o ILogger
, veja Logging em C# e .NET e exemplos de código.
O Exportador do Azure Monitor não inclui nenhuma biblioteca de instrumentação.
Você pode coletar dependências dos Kits de Desenvolvimento de Software (SDKs) do Azure usando o exemplo de código a seguir para assinar manualmente a fonte.
// 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();
Para reduzir ou aumentar o número de logs enviados ao Azure Monitor, configure o log para definir o nível de log apropriado ou aplicar filtros. Por exemplo, você pode optar por enviar somente Warning
e Error
logs para o OpenTelemetry/Azure Monitor. O OpenTelemetry não controla o roteamento ou a filtragem de logs . Sua ILogger
configuração toma essas decisões. Para obter mais informações sobre a configuração ILogger
, veja Configurar registro.
Solicitações
- Consumidores do JMS (Java Message Service)
- Consumidores do Kafka
- Netty
- Quartzo
- RabbitMQ
- Servlets
- Agendamento de Primavera
Observação
A autoinstrumentação Servlet e Netty abrange a maioria dos serviços HTTP Java, incluindo Java EE, Jakarta EE, Spring Boot, Quarkus e Micronaut
.
Dependências (mais propagação de rastreamento distribuída a jusante)
- Apache HttpClient
- Apache HttpAsyncClient
- AsyncHttpClient
- Google HttpClient
- gRPC
- java.net.HttpURLConnection
- Java 11 HttpClient
- Cliente JAX-RS
- Cliente HTTP Jetty
- JMS (Java Message Service)
- Kafka
- Cliente Netty
- OkHttp
- RabbitMQ
Dependências (sem propagação de rastreamento distribuída a jusante)
- Dá suporte ao Cassandra
- Dá suporte à Conectividade de Banco de Dados Java (JDBC)
- Dá suporte ao MongoDB (assíncrono e sincronização)
- Suporte para Redis (Lettuce e Jedis)
Métricas
- Métricas de micrômetro, incluindo métricas de atuador de mola
- Métricas de JMX (Extensões de Gerenciamento de Java)
Logs
- Logback (incluindo propriedades MDC) ¹
- Log4j (incluindo propriedades MDC/Thread Context) ¹
- JBoss Logging (incluindo propriedades MDC) ¹
- java.util.logging ¹
Para reduzir ou aumentar o número de logs coletados pelo Azure Monitor, primeiro defina o nível de log desejado (como WARNING
ou ERROR
) na biblioteca de logs do aplicativo.
Coleção padrão
A telemetria emitida pelos seguintes SDKs do Azure é coletada automaticamente por padrão:
[//]: # "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)"
Solicitações para aplicativos nativos do Spring Boot
- Spring Web
- Spring Web MVC (Model-View-Controller)
- Spring WebFlux
Dependências para aplicativos nativos do Spring Boot
Métricas
Logs para aplicativos nativos do Spring Boot
Para reduzir ou aumentar o número de logs coletados pelo Azure Monitor, primeiro defina o nível de log desejado (como WARNING
ou ERROR
) na biblioteca de logs do aplicativo.
Para aplicativos nativos do Quartz, confira a documentação do Quarkus.
As seguintes bibliotecas de instrumentação OpenTelemetry estão incluídas como parte do Azure Monitor Application Insights Distro. Para obter mais informações, confira SDK do Azure para JavaScript.
Solicitações
Dependências
Logs
Para reduzir ou aumentar o número de logs coletados pelo Azure Monitor, primeiro defina o nível de log desejado (como WARNING
ou ERROR
) na biblioteca de logs do aplicativo.
As instrumentações podem ser configuradas usando AzureMonitorOpenTelemetryOptions
:
// Import Azure Monitor OpenTelemetry
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
// Import OpenTelemetry HTTP Instrumentation to get config type
const { HttpInstrumentationConfig } = require("@azure/monitor-opentelemetry");
// Import HTTP to get type
const { IncomingMessage } = require("http");
// Specific Instrumentation configs could be added
const httpInstrumentationConfig: HttpInstrumentationConfig = {
ignoreIncomingRequestHook: (request: IncomingMessage) => {
return false; //Return true if you want to ignore a specific request
},
enabled: true
};
// Instrumentations configuration
const options: AzureMonitorOpenTelemetryOptions = {
instrumentationOptions: {
http: httpInstrumentationConfig,
azureSdk: { enabled: true },
mongoDb: { enabled: true },
mySql: { enabled: true },
postgreSql: { enabled: true },
redis: { enabled: true },
redis4: { enabled: true },
}
};
// Enable Azure Monitor integration
useAzureMonitor(options);
Solicitações
Dependências
Logs
Para reduzir ou aumentar o número de logs coletados pelo Azure Monitor, primeiro defina o nível de log desejado (como WARNING
ou ERROR
) na biblioteca de logs do aplicativo.
Os exemplos de uso da biblioteca de registro em log do Python podem ser encontrados no GitHub.
A telemetria emitida pelos SDKs (Kits de Desenvolvimento de Software) do Azure é coletada automaticamente por padrão.
Notas de rodapé
- ¹: dá suporte a relatórios automáticos de exceções não tratadas/não detectadas
- ²: dá suporte a métricas do OpenTelemetry
Dica
Todas as métricas do OpenTelemetry, sejam coletadas automaticamente de bibliotecas de instrumentação ou coletadas manualmente da codificação personalizada, atualmente são consideradas "métricas personalizadas" do Application Insights para fins de cobrança. Saiba mais.
Você pode coletar mais dados automaticamente quando incluir as bibliotecas de instrumentação da comunidade OpenTelemetry.
Cuidado
Não damos suporte nem garantimos a qualidade das bibliotecas de instrumentação da comunidade. Para sugerir uma para nossa distribuição, faça uma postagem ou vote a favor em nossa comunidade de comentários. Esteja ciente de que algumas são baseadas em especificações experimentais do OpenTelemetry e podem introduzir mudanças significativas no futuro.
Para adicionar uma biblioteca de comunidade, use os métodos ConfigureOpenTelemetryMeterProvider
ou ConfigureOpenTelemetryTracerProvider
depois de adicionar o pacote NuGet à biblioteca.
O exemplo a seguir demonstra como a Instrumentação em Tempo de Execução pode ser adicionada para coletar métricas adicionais.
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();
O exemplo a seguir demonstra como a Instrumentação em Tempo de Execução pode ser adicionada para coletar métricas adicionais.
// 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();
Você não pode estender a distribuição Java com bibliotecas de instrumentação da comunidade. Para solicitar a inclusão de outra biblioteca de instrumentação, abra um problema em nossa página do GitHub. Você pode encontrar um link para a nossa página do GitHub nas Próximas etapas.
Você não pode usar bibliotecas de instrumentação da comunidade com aplicativos nativos Java do GraalVM.
Outras Instrumentações do OpenTelemetry estão disponíveis aqui e podem ser adicionadas usando o TraceHandler no ApplicationInsightsClient:
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics, trace, ProxyTracerProvider } = require("@opentelemetry/api");
// Import the OpenTelemetry instrumentation registration function and Express instrumentation
const { registerInstrumentations } = require( "@opentelemetry/instrumentation");
const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
// Get the OpenTelemetry tracer provider and meter provider
const tracerProvider = (trace.getTracerProvider() as ProxyTracerProvider).getDelegate();
const meterProvider = metrics.getMeterProvider();
// Enable Azure Monitor integration
useAzureMonitor();
// Register the Express instrumentation
registerInstrumentations({
// List of instrumentations to register
instrumentations: [
new ExpressInstrumentation(), // Express instrumentation
],
// OpenTelemetry tracer provider
tracerProvider: tracerProvider,
// OpenTelemetry meter provider
meterProvider: meterProvider
});
Para adicionar uma biblioteca de instrumentação da comunidade (não oficialmente suportada/incluída na distribuição do Azure Monitor), você pode instrumentar diretamente com as instrumentações. A lista de bibliotecas de instrumentação da comunidade pode ser encontrada aqui.
Observação
Não é recomendado instrumentar manualmente uma biblioteca de instrumentação suportada com instrument()
e a distribuição configure_azure_monitor()
. Não é um cenário suportado e você pode obter um comportamento indesejado em sua telemetria.
# 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())
Coletar telemetria personalizada
Esta seção explica como coletar telemetria personalizada do aplicativo.
Dependendo do idioma e do tipo de sinal, há diferentes maneiras de coletar telemetria personalizada, incluindo:
- API do OpenTelemetry
- Bibliotecas de registro/métricas específicas de idioma
- API Clássica do Application Insights
A seguinte tabela representa os tipos de telemetria personalizada com suporte no momento:
Idioma |
Eventos personalizados |
Métricas personalizadas |
Dependências |
Exceções |
Visualizações de página |
Solicitações |
Rastreamentos |
ASP.NET Core |
|
|
|
|
|
|
|
API do OpenTelemetry |
|
Sim |
Sim |
Sim |
|
Sim |
|
API ILogger |
|
|
|
|
|
|
Sim |
API clássica de IA |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Java |
|
|
|
|
|
|
|
API do OpenTelemetry |
|
Sim |
Sim |
Sim |
|
Sim |
|
Logback, Log4j , JUL |
|
|
|
Sim |
|
|
Sim |
Métricas do Micrometer |
|
Sim |
|
|
|
|
|
API clássica de IA |
Sim |
Sim |
Sim |
Sim |
Sim |
Sim |
Sim |
|
|
|
|
|
|
|
|
Node.js |
|
|
|
|
|
|
|
API do OpenTelemetry |
|
Sim |
Sim |
Sim |
|
Sim |
|
|
|
|
|
|
|
|
|
Python |
|
|
|
|
|
|
|
API do OpenTelemetry |
|
Sim |
Sim |
Sim |
|
Sim |
|
Módulo de registro Python |
|
|
|
|
|
|
Sim |
Extensão de eventos |
Sim |
|
|
|
|
|
Sim |
Observação
O Application Insights Java 3.x e o Application Insights Node.js 3.x coletam telemetria da API Clássica do Application Insights. Esse comportamento simplifica as atualizações e dá suporte temporariamente à telemetria personalizada até que a API OpenTelemetry inclua todos os tipos de telemetria personalizados.
Adicionar métricas personalizadas
Nesse contexto, o termo de métricas personalizadas refere-se a instrumentar manualmente seu código para coletar métricas extras além do que as Bibliotecas de Instrumentação OpenTelemetry coletam automaticamente.
A API do OpenTelemetry oferece seis “instrumentos” métricos para cobrir vários cenários métricos e você precisa escolher o “Tipo de Agregação” correto ao visualizar as métricas no Metrics Explorer. Esse requisito é válido ao usar a API de Métrica do OpenTelemetry para enviar métricas e ao usar uma biblioteca de instrumentação.
A tabela a seguir mostra os tipos de agregação recomendados para cada um dos Instrumentos de Métrica do OpenTelemetry.
Instrumento do OpenTelemetry |
Tipo de agregação do Azure Monitor |
Contador |
Soma |
Contador assíncrono |
Soma |
Histograma |
Min, Max, Média, Soma e Contagem |
Medidor assíncrono |
Média |
UpDownCounter |
Soma |
Contador Assíncrono UpDownCounter |
Soma |
Cuidado
Outros tipos de agregação não são significativos na maioria dos casos.
A Especificação do OpenTelemetry descreve os instrumentos e fornece exemplos de quando usar cada um deles.
Dica
O histograma é o mais versátil e mais equivalente à Application Insights GetMetric API Clássica. Atualmente, o Azure Monitor nivela o instrumento de histograma em nossos cinco tipos de agregação suportados, e o suporte para percentis está em andamento. Embora menos versátil, outros instrumentos OpenTelemetry têm um efeito menor no desempenho do aplicativo.
Exemplo de histograma
A inicialização do aplicativo deve se inscrever em um medidor por nome:
// 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();
O Meter
deve ser inicializado usando esse mesmo nome:
// 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);
}
}
Injetar OpenTelemetry
:
Criar um histograma:
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
histogram.record(1.0);
histogram.record(100.0);
histogram.record(30.0);
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the meter for the "testMeter" namespace
const meter = metrics.getMeter("testMeter");
// Create a histogram metric
let histogram = meter.createHistogram("histogram");
// Record values to the histogram metric with different tags
histogram.record(1, { "testKey": "testValue" });
histogram.record(30, { "testKey": "testValue2" });
histogram.record(100, { "testKey2": "testValue" });
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
import os
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_histogram_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_histogram_demo")
# Record three values to the histogram.
histogram = meter.create_histogram("histogram")
histogram.record(1.0, {"test_key": "test_value"})
histogram.record(100.0, {"test_key2": "test_value"})
histogram.record(30.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
Exemplo de contador
A inicialização do aplicativo deve se inscrever em um medidor por nome:
// 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();
O Meter
deve ser inicializado usando esse mesmo nome:
// 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"));
}
}
Injetar OpenTelemetry
:
Criar o contador:
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"));
// Import the Azure Monitor OpenTelemetry plugin and OpenTelemetry API
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration
useAzureMonitor();
// Get the meter for the "testMeter" namespace
const meter = metrics.getMeter("testMeter");
// Create a counter metric
let counter = meter.createCounter("counter");
// Add values to the counter metric with different tags
counter.add(1, { "testKey": "testValue" });
counter.add(5, { "testKey2": "testValue" });
counter.add(3, { "testKey": "testValue2" });
# Import the `configure_azure_monitor()` and `metrics` functions from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
import os
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_counter_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_counter_demo")
# Create a counter metric with the name "counter".
counter = meter.create_counter("counter")
# Add three values to the counter.
# The first argument to the `add()` method is the value to add.
# The second argument is a dictionary of dimensions.
# Dimensions are used to group related metrics together.
counter.add(1.0, {"test_key": "test_value"})
counter.add(5.0, {"test_key2": "test_value"})
counter.add(3.0, {"test_key": "test_value2"})
# Wait for background execution.
input()
Exemplo de medidor
A inicialização do aplicativo deve se inscrever em um medidor por nome:
// 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();
O Meter
deve ser inicializado usando esse mesmo nome:
// 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"));
});
}
}
Injetar OpenTelemetry
:
Criar um medidor:
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"));
});
// Import the useAzureMonitor function and the metrics module from the @azure/monitor-opentelemetry and @opentelemetry/api packages, respectively.
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { metrics } = require("@opentelemetry/api");
// Enable Azure Monitor integration.
useAzureMonitor();
// Get the meter for the "testMeter" meter name.
const meter = metrics.getMeter("testMeter");
// Create an observable gauge metric with the name "gauge".
let gauge = meter.createObservableGauge("gauge");
// Add a callback to the gauge metric. The callback will be invoked periodically to generate a new value for the gauge metric.
gauge.addCallback((observableResult: ObservableResult) => {
// Generate a random number between 0 and 99.
let randomNumber = Math.floor(Math.random() * 100);
// Set the value of the gauge metric to the random number.
observableResult.observe(randomNumber, {"testKey": "testValue"});
});
# Import the necessary packages.
from typing import Iterable
import os
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import metrics
from opentelemetry.metrics import CallbackOptions, Observation
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Opt in to allow grouping of your metrics via a custom metrics namespace in app insights metrics explorer.
# Specify the namespace name using get_meter("namespace-name")
os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
# Get a meter provider and a meter with the name "otel_azure_monitor_gauge_demo".
meter = metrics.get_meter_provider().get_meter("otel_azure_monitor_gauge_demo")
# Define two observable gauge generators.
# The first generator yields a single observation with the value 9.
# The second generator yields a sequence of 10 observations with the value 9 and a different dimension value for each observation.
def observable_gauge_generator(options: CallbackOptions) -> Iterable[Observation]:
yield Observation(9, {"test_key": "test_value"})
def observable_gauge_sequence(options: CallbackOptions) -> Iterable[Observation]:
observations = []
for i in range(10):
observations.append(
Observation(9, {"test_key": i})
)
return observations
# Create two observable gauges using the defined generators.
gauge = meter.create_observable_gauge("gauge", [observable_gauge_generator])
gauge2 = meter.create_observable_gauge("gauge2", [observable_gauge_sequence])
# Wait for background execution.
input()
Adicionar exceções personalizadas
Selecione as bibliotecas de instrumentação para reportar automaticamente as exceções ao Application Insights.
No entanto, talvez você queira relatar manualmente exceções além daquelas relatadas pelas bibliotecas de instrumentação.
Por exemplo, exceções capturadas pelo seu código normalmente não são reportadas. Talvez você queira relatá-los para chamar a atenção em experiências relevantes, incluindo a seção de falhas e visualizações de transações de ponta a ponta.
Para registrar uma exceção usando uma atividade:
// 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);
}
}
Para registrar uma exceção usando o 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" });
}
Para registrar uma exceção usando uma atividade:
// 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);
}
}
Para registrar uma exceção usando o 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" });
}
Você pode usar opentelemetry-api
para atualizar o status de um intervalo e registrar as exceções.
Adicione opentelemetry-api-1.0.0.jar
(ou posterior) ao seu aplicativo:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Defina o status como error
e registre uma exceção no código:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
Defina o status como error
e registre uma exceção no código:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);
O Node.js SDK exporta exceções baseadas em intervalo registradas manualmente para o Application Insights como exceções somente quando registradas em um intervalo de nível superior ou em um filho de um intervalo remoto ou interno.
// 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);
}
O SDK do Python do OpenTelemetry é implementado de tal forma que as exceções lançadas são automaticamente capturadas e registradas. Veja o código de exemplo a seguir para obter um exemplo desse comportamento:
# 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")
Se desejar registrar exceções manualmente, desabilite essa opção no gerenciador de contexto e use record_exception()
diretamente, conforme mostrado no exemplo a seguir:
...
# 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)
...
Adicionar intervalos personalizados
Talvez você queira adicionar um intervalo personalizado em dois cenários. Primeiro, quando há uma solicitação de dependência que ainda não foi coletada por uma biblioteca de instrumentação. Segundo, quando você deseja modelar um processo de aplicação como um intervalo na visão de transação de ponta a ponta.
Observação
As classes Activity
e ActivitySource
do namespace System.Diagnostics
representam os conceitos Span
e Tracer
do OpenTelemetry, respectivamente. Você cria ActivitySource
diretamente usando o construtor dele em vez de usar TracerProvider
. Cada classe ActivitySource
deve ser conectada explicitamente ao TracerProvider
usando AddSource()
. Isso ocorre porque partes da API de rastreamento do OpenTelemetry são incorporadas diretamente ao runtime do .NET. Para saber mais, confira Introdução à API de rastreamento do OpenTelemetry .NET.
// Define an activity source named "ActivitySourceName". This activity source will be used to create activities for all requests to the application.
internal static readonly ActivitySource activitySource = new("ActivitySourceName");
// Create an ASP.NET Core application builder.
var builder = WebApplication.CreateBuilder(args);
// Configure the OpenTelemetry tracer provider to add a source named "ActivitySourceName". This will ensure that all activities created by the activity source are traced.
builder.Services.ConfigureOpenTelemetryTracerProvider((sp, builder) => builder.AddSource("ActivitySourceName"));
// Add the Azure Monitor telemetry service to the application. This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Build the ASP.NET Core application.
var app = builder.Build();
// Map a GET request to the root path ("/") to the specified action.
app.MapGet("/", () =>
{
// Start a new activity named "CustomActivity". This activity will be traced and the trace data will be sent to Azure Monitor.
using (var activity = activitySource.StartActivity("CustomActivity"))
{
// your code here
}
// Return a response message.
return $"Hello World!";
});
// Start the ASP.NET Core application.
app.Run();
StartActivity
tem ActivityKind.Internal
como padrão, mas você pode fornecer qualquer outro ActivityKind
.
ActivityKind.Client
, ActivityKind.Producer
e ActivityKind.Internal
são mapeados para o Application Insights dependencies
.
ActivityKind.Server
e ActivityKind.Consumer
são mapeados para o Application Insights requests
.
Observação
As classes Activity
e ActivitySource
do namespace System.Diagnostics
representam os conceitos Span
e Tracer
do OpenTelemetry, respectivamente. Você cria ActivitySource
diretamente usando o construtor dele em vez de usar TracerProvider
. Cada classe ActivitySource
deve ser conectada explicitamente ao TracerProvider
usando AddSource()
. Isso ocorre porque partes da API de rastreamento do OpenTelemetry são incorporadas diretamente ao runtime do .NET. Para saber mais, confira Introdução à API de rastreamento do OpenTelemetry .NET.
// Create an OpenTelemetry tracer provider builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("ActivitySourceName")
.AddAzureMonitorTraceExporter()
.Build();
// Create an activity source named "ActivitySourceName".
var activitySource = new ActivitySource("ActivitySourceName");
// Start a new activity named "CustomActivity". This activity will be traced and the trace data will be sent to Azure Monitor.
using (var activity = activitySource.StartActivity("CustomActivity"))
{
// your code here
}
StartActivity
tem ActivityKind.Internal
como padrão, mas você pode fornecer qualquer outro ActivityKind
.
ActivityKind.Client
, ActivityKind.Producer
e ActivityKind.Internal
são mapeados para o Application Insights dependencies
.
ActivityKind.Server
e ActivityKind.Consumer
são mapeados para o Application Insights requests
.
Use a anotação OpenTelemetry
A maneira mais simples de adicionar os seus próprios intervalos é usando a anotação @WithSpan
do OpenTelemetry.
Os spans preenchem as tabelas requests
e dependencies
no Application Insights.
Adicione opentelemetry-instrumentation-annotations-1.32.0.jar
(ou posterior) ao seu aplicativo:
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-annotations</artifactId>
<version>1.32.0</version>
</dependency>
Use a anotação @WithSpan
para emitir um intervalo sempre que seu método for executado:
import io.opentelemetry.instrumentation.annotations.WithSpan;
@WithSpan(value = "your span name")
public void yourMethod() {
}
Por padrão, o intervalo acaba na tabela dependencies
com o tipo de dependência InProc
.
Para métodos que representam um trabalho em segundo plano não capturado pela instrumentação automática, recomendamos aplicar o atributo kind = SpanKind.SERVER
à anotação @WithSpan
para garantir que eles apareçam na tabela requests
do Application Insights.
Usar a API OpenTelemetry
Se a anotação @WithSpan
do OpenTelemetry acima não atender às suas necessidades, adicione seus intervalos usando a API do OpenTelemetry.
Adicione opentelemetry-api-1.0.0.jar
(ou posterior) ao seu aplicativo:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Use a classe GlobalOpenTelemetry
para criar um Tracer
:
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = GlobalOpenTelemetry.getTracer("com.example");
Crie um intervalo, torne-o atual e, em seguida, encerre-o:
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();
}
Injetar OpenTelemetry
:
Criar um Tracer
:
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = openTelemetry.getTracer("com.example");
Crie um intervalo, torne-o atual e, em seguida, encerre-o:
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();
A API do OpenTelemetry pode ser usada para adicionar seus próprios intervalos, que aparecem nas tabelas requests
e dependencies
no Application Insights.
O exemplo de código mostra como usar o método tracer.start_as_current_span()
para iniciar, tornar o intervalo atual e terminar o intervalo dentro de seu contexto.
...
# 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)
...
Por padrão, o intervalo está na tabela dependencies
com um tipo de dependência de InProc
.
Se seu método representar um trabalho em segundo plano que ainda não foi capturado pela instrumentação automática, recomendamos definir o atributo kind = SpanKind.SERVER
para garantir que ele apareça na tabela requests
do Application Insights .
...
# 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.
...
Enviar eventos personalizados
O Application Insights armazena eventos personalizados na customEvents
tabela. Uma maneira de analisá-las, filtrar e visualizá-las é usando as experiências de uso do Application Insights.
Se você quiser automatizar a coleção de eventos de interação do lado do cliente, poderá usar o plug-in no SDK do JavaScript.
Os eventos personalizados estão em Visualização Pública e uso Azure.Monitor.OpenTelemetry.AspNetCore
1.3.0-beta.3.
Para enviar um CustomEvent
usando ILogger
, defina o atributo "microsoft.custom_event.name"
no modelo de mensagem.
// 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");
Os eventos personalizados estão em Visualização Pública e uso Azure.Monitor.OpenTelemetry.Exporter
1.4.0-beta.3.
Para enviar um CustomEvent
usando ILogger
, defina o atributo "microsoft.custom_event.name"
no modelo de mensagem.
// 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");
Para enviar um customEvent
com o agente Java, defina o atributo "microsoft.custom_event.name"
no registro de log do OpenTelemetry.
Dependendo se o agente Java do Application Insights está em uso ou o SDK de configuração automática, a maneira de buscar o registrador do OpenTelemetry é ligeiramente diferente. Esse detalhe é explicado mais adiante nos exemplos a seguir.
Para o agente java do 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();
Para o SDK de configuração automática:
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();
Para emitir eventos personalizados de forma confiável, use a API OpenTelemetry diretamente. Algumas estruturas de log não dão suporte à anexação ou análise do atributo de eventos personalizados.
Não é possível enviar um customEvent
usando o atributo "microsoft.custom_event.name"
no Java nativo.
Para enviar um customEvent
usando logger.emit
, defina o atributo "microsoft.custom_event.name"
no objeto attributes
do log. Outros atributos também podem ser incluídos conforme necessário.
// Send a customEvent by including the microsoft attribute key in the log.
// The customEvent name uses the value of that attribute.
logger.emit({
body: 'Hello World!',
attributes: {
"microsoft.custom_event.name": "test-event-name",
"additional_attrs": "val1"
},
});
// You can also populate fields like client_IP with attribute `client.address`
logger.emit({
body: 'This entry will have a custom client_IP',
attributes: {
"microsoft.custom_event.name": "test_event",
"client.address": "192.168.1.1"
},
});
Para enviar um customEvent
em Python, use a biblioteca de registro com o atributo "microsoft.custom_event.name"
no parâmetro 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"
}
)
Modificar telemetria
Esta seção explica como modificar a telemetria.
Adicionar atributos de intervalo
Esses atributos podem incluir a adição de uma propriedade personalizada à telemetria. Você também pode usar atributos para definir campos opcionais no esquema do Application Insights, como IP do Cliente.
Adicionar uma propriedade personalizada a um Span
Todos os atributos adicionados aos intervalos são exportados como propriedades personalizadas. Elas preenchem o campo customDimensions na tabela de solicitações, dependências, rastreamentos ou exceções.
Para adicionar atributos de span, use uma das duas maneiras a seguir:
Dica
A vantagem de usar as opções fornecidas pelas bibliotecas de instrumentação, quando disponíveis, é que todo o contexto fica disponível. Assim, os usuários podem optar por adicionar ou filtrar mais atributos. Por exemplo, a opção de enriquecimento na biblioteca de instrumentação do HttpClient oferece aos usuários acesso ao HttpRequestMessage e ao próprio HttpResponseMessage. Eles podem selecionar qualquer coisa nela e armazenar como um atributo.
Muitas bibliotecas de instrumentação oferecem uma opção de enriquecimento. Para obter diretrizes, confira os arquivos Leiame das bibliotecas de instrumentação individuais:
Usar um processador personalizado:
Dica
Adicione o processador mostrado aqui antes de adicionar o 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();
Adicione ActivityEnrichingProcessor.cs
ao seu projeto com o seguinte código:
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");
}
}
Para adicionar atributos de span, use uma das duas maneiras a seguir:
- Use opções fornecidas pelas bibliotecas de instrumentação.
- Adicione um processador de span personalizado.
Dica
A vantagem de usar as opções fornecidas pelas bibliotecas de instrumentação, quando disponíveis, é que todo o contexto fica disponível. Assim, os usuários podem optar por adicionar ou filtrar mais atributos. Por exemplo, a opção "enriquecer" na biblioteca de instrumentação do HttpClient oferece aos usuários acesso ao próprio httpRequestMessage. Eles podem selecionar qualquer coisa nela e armazenar como um atributo.
Muitas bibliotecas de instrumentação oferecem uma opção de enriquecimento. Para obter diretrizes, confira os arquivos Leiame das bibliotecas de instrumentação individuais:
Usar um processador personalizado:
Dica
Adicione o processador mostrado aqui antes do Exportador do 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();
Adicione ActivityEnrichingProcessor.cs
ao seu projeto com o seguinte código:
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");
}
}
Você pode usar opentelemetry-api
para adicionar atributos a elementos span.
Adicionar um ou mais atributos de intervalo preenche o campo customDimensions
na tabela requests
, dependencies
, traces
ou exceptions
.
Adicione opentelemetry-api-1.0.0.jar
(ou posterior) ao seu aplicativo:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Adicione dimensões personalizadas ao seu código:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
Adicione dimensões personalizadas ao seu código:
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;
AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");
// Import the necessary packages.
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const { ReadableSpan, Span, SpanProcessor } = require("@opentelemetry/sdk-trace-base");
const { SemanticAttributes } = require("@opentelemetry/semantic-conventions");
// 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: ReadableSpan) {
// Add custom dimensions to the span.
span.attributes["CustomDimension1"] = "value1";
span.attributes["CustomDimension2"] = "value2";
}
}
// Enable Azure Monitor integration.
const options: AzureMonitorOpenTelemetryOptions = {
// Add the SpanEnrichingProcessor
spanProcessors: [new SpanEnrichingProcessor()]
}
useAzureMonitor(options);
Usar um processador personalizado:
...
# 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],
)
...
Adicione SpanEnrichingProcessor
ao seu projeto com o seguinte código:
# 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"
Definir o IP do usuário
Você pode preencher o campo client_IP de solicitações definindo um atributo no span. A Application Insights usa o endereço IP para gerar atributos de localização do usuário e, em seguida, o descarta por padrão.
Use o exemplo de propriedade personalizada, mas substitua as seguintes linhas de código em 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>");
Use o exemplo de propriedade personalizada, mas substitua as seguintes linhas de código em 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>");
O Java preenche automaticamente esse campo.
Este campo é preenchido automaticamente.
Use o exemplo de propriedade personalizada, mas substitua as seguintes linhas de código:
...
// 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>";
}
}
Use o exemplo de propriedade personalizada, mas substitua as seguintes linhas de código em SpanEnrichingProcessor.py
:
# Set the `http.client_ip` attribute of the span to the specified IP address.
span._attributes["http.client_ip"] = "<IP Address>"
Definir a ID do usuário ou a ID do usuário autenticado
Você pode preencher o campo user_Id ou user_AuthenticatedId para solicitações usando as diretrizes a seguir. A ID do usuário é um identificador de usuário anônimo. A ID do usuário autenticado é um identificador de usuário conhecido.
Importante
Veja as leis de privacidade aplicáveis antes de configurar a ID de Usuário autenticado.
Preencha o campo user ID
na tabela requests
, dependencies
ou exceptions
.
Adicione opentelemetry-api-1.0.0.jar
(ou posterior) ao seu aplicativo:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Defina user_Id
no seu código:
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser");
Preencha o campo user ID
na tabela requests
, dependencies
ou exceptions
.
Defina user_Id
no seu código:
import io.opentelemetry.api.trace.Span;
Span.current().setAttribute("enduser.id", "myuser");
Use o exemplo de propriedade personalizada, mas substitua as seguintes linhas de código:
...
// 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>";
}
}
Use o exemplo de propriedade personalizada, mas substitua as seguintes linhas de código:
# Set the `enduser.id` attribute of the span to the specified user ID.
span._attributes["enduser.id"] = "<User ID>"
Adicionar atributos de log
OpenTelemetry usa .NET ILogger
.
A anexação de dimensões personalizadas aos registros pode ser realizada usando um modelo de mensagem.
OpenTelemetry usa .NET ILogger
.
A anexação de dimensões personalizadas aos registros pode ser realizada usando um modelo de mensagem.
Logback, Log4j e java.util.logging são instrumentados automaticamente. Anexar dimensões personalizadas aos logs pode ser realizado destas maneiras:
Para aplicativos nativos do Spring Boot, o Logback já vem instrumentado e pronto para uso.
const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
const bunyan = require('bunyan');
// Instrumentations configuration
const options: AzureMonitorOpenTelemetryOptions = {
instrumentationOptions: {
// Instrumentations generating logs
bunyan: { enabled: true },
}
};
// Enable Azure Monitor integration
useAzureMonitor(options);
var log = bunyan.createLogger({ name: 'testApp' });
log.info({
"testAttribute1": "testValue1",
"testAttribute2": "testValue2",
"testAttribute3": "testValue3"
}, 'testEvent');
A biblioteca Python logging é autoinstrumentada. É possível anexar dimensões personalizadas aos seus logs passando um dicionário para o argumento extra
de seus logs:
...
# Create a warning log message with the properties "key1" and "value1".
logger.warning("WARNING: Warning log with properties", extra={"key1": "value1"})
...
Obter o ID do rastreamento ou o ID do intervalo
Você pode obter o Trace ID
e o Span ID
do Span atualmente ativo seguindo os seguintes passos.
Observação
As classes Activity
e ActivitySource
do namespace System.Diagnostics
representam os conceitos Span
e Tracer
do OpenTelemetry, respectivamente. Isso ocorre porque partes da API de rastreamento do OpenTelemetry são incorporadas diretamente ao runtime do .NET. Para saber mais, confira Introdução à API de rastreamento do OpenTelemetry .NET.
// Get the current activity.
Activity activity = Activity.Current;
// Get the trace ID of the activity.
string traceId = activity?.TraceId.ToHexString();
// Get the span ID of the activity.
string spanId = activity?.SpanId.ToHexString();
Observação
As classes Activity
e ActivitySource
do namespace System.Diagnostics
representam os conceitos Span
e Tracer
do OpenTelemetry, respectivamente. Isso ocorre porque partes da API de rastreamento do OpenTelemetry são incorporadas diretamente ao runtime do .NET. Para saber mais, confira Introdução à API de rastreamento do OpenTelemetry .NET.
// Get the current activity.
Activity activity = Activity.Current;
// Get the trace ID of the activity.
string traceId = activity?.TraceId.ToHexString();
// Get the span ID of the activity.
string spanId = activity?.SpanId.ToHexString();
Você pode usar opentelemetry-api
para obter o ID do rastreamento ou o ID do intervalo.
Adicione opentelemetry-api-1.0.0.jar
(ou posterior) ao seu aplicativo:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Obtenha o ID de rastreamento da solicitação e o ID do intervalo no seu código:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
Obtenha o ID de rastreamento da solicitação e o ID do intervalo no seu código:
import io.opentelemetry.api.trace.Span;
Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();
Obtenha o ID de rastreamento da solicitação e o ID do intervalo no seu código:
// 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;
Obtenha o ID de rastreamento da solicitação e o ID do intervalo no seu código:
# 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
Próximas etapas
- Para configurar ainda mais a Distribuição do OpenTelemetry, confira Configuração do OpenTelemetry do Azure Monitor.
- Para revisar o código-fonte, acesse o repositório do GitHub AspNetCore do Azure Monitor.
- Para instalar o pacote NuGet, verificar se há atualizações ou exibir as notas de versão, consulte a página Pacote NuGet AspNetCore do Azure Monitor.
- Para ficar mais familiarizado com o Azure Monitor e o OpenTelemetry, confira o aplicativo de exemplo do Azure Monitor.
- Para saber mais sobre o OpenTelemetry e a respectiva comunidade, confira o Repositório GitHub do .NET do OpenTelemetry.
- Para habilitar experiências de uso, habilite o monitoramento do usuário no navegador ou na Web.
- Para revisar perguntas frequentes, etapas de solução de problemas, opções de suporte ou fornecer comentários do OpenTelemetry, veja a ajuda, o suporte e o comentários do OpenTelemetry para o Azure Monitor Application Insights.
- Para configurar ainda mais a Distribuição do OpenTelemetry, confira Configuração do OpenTelemetry do Azure Monitor
- Para examinar o código-fonte, confira o Repositório do GitHub do Exportador do Azure Monitor.
- Para instalar o pacote de NuGet, verificar se há atualizações ou exibir notas de versão, visite a página Pacote de NuGet do Exportador do Azure Monitor.
- Para ficar mais familiarizado com o Azure Monitor e o OpenTelemetry, confira o aplicativo de exemplo do Azure Monitor.
- Para saber mais sobre o OpenTelemetry e a respectiva comunidade, confira o Repositório GitHub do .NET do OpenTelemetry.
- Para habilitar experiências de uso, habilite o monitoramento do usuário no navegador ou na Web.
- Para revisar perguntas frequentes, etapas de solução de problemas, opções de suporte ou fornecer comentários do OpenTelemetry, veja a ajuda, o suporte e o comentários do OpenTelemetry para o Azure Monitor Application Insights.
- Para revisar o código-fonte e a documentação adicional, acesse o Repositório do GitHub da Distribuição do Azure Monitor.
- Para ver exemplos adicionais e casos de uso, confira Amostras da Distribuição do Azure Monitor.
- Para ver as notas sobre a versão, confira as notas sobre a versão no GitHub.
- Para instalar o pacote de PyPI, verificar se há atualizações e exibir notas sobre a versão, veja a página Pacote de PyPI de Distribuição do Azure Monitor.
- Para se familiarizar com o Application Insights do Azure Monitor e o OpenTelemetry, confira oAplicativo de exemplo do Azure Monitor.
- Para saber mais sobre o OpenTelemetry e a respectiva comunidade, confira o repositório GitHub em Python para OpenTelemetry.
- Para ver as instrumentações e os componentes do OpenTelemetry disponíveis, acesse o Repositório do GitHub do Colaborador do Python do OpenTelemetry.
- Para habilitar experiências de uso, habilite o monitoramento do usuário no navegador ou na Web.
- Para revisar perguntas frequentes, etapas de solução de problemas, opções de suporte ou fornecer comentários do OpenTelemetry, veja a ajuda, o suporte e o comentários do OpenTelemetry para o Azure Monitor Application Insights.