Este guia fornece instruções sobre como integrar e personalizar a instrumentação OpenTelemetry (OTel) no Azure Monitor Application Insights.
Para saber mais sobre os conceitos do OpenTelemetria, consulte a visão geral do OpenTelemetry ou as Perguntas frequentes do OpenTelemetry .
Recolha de dados automática
As distribuições coletam dados automaticamente integrando bibliotecas de instrumentação OpenTelemetry.
Bibliotecas de instrumentação incluídas
Pedidos
Dependências
Registo
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 filtragem de logs - sua ILogger configuração toma essas decisões. Para obter mais informações sobre configurar ILogger, consulte Configurar registo.
Para obter mais informações sobre ILogger, consulte Registo de logs 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 SDKs (Software Development Kits) 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 filtragem de logs - sua ILogger configuração toma essas decisões. Para obter mais informações sobre configurar ILogger, consulte Configurar registo.
Pedidos
- Consumidores do Java Message Service (JMS)
- Consumidores do Kafka
- Netty
- Quartzo
- RabbitMQ
- Servlets
- Programação de primavera
Nota
A autoinstrumentação de Servlet e Netty cobre a maioria dos serviços HTTP Java, incluindo Java EE, Jakarta EE, Spring Boot, Quarkus e Micronaut.
Dependências (mais propagação de traços distribuídos no fluxo descendente)
- Apache HttpClient
- Apache HttpAsyncClient
- AsyncHttpClient
- Google HttpClient
- gRPC
- java.net.HttpURLConnection
- Java 11 HttpClient
- Cliente JAX-RS
- Cais HttpClient
- JMS (Serviço de Mensagens Java)
- Kafka
- Cliente Netty
- OkHttp
- RabbitMQ
Dependências (sem propagação de rastreamento distribuído downstream)
- Suporta Cassandra
- Suporta conectividade de banco de dados Java (JDBC)
- Suporta MongoDB (assíncrono e síncrono)
- Suporta Redis (Lettuce e Jedis)
Métricas
- Métricas do Micrometer, incluindo métricas do Spring Boot Actuator
- Métricas JMX (Java Management Extensions)
Registos
- 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 que o Monitor do Azure coleta, primeiro defina o nível de log desejado (como WARNING ou ERROR) na biblioteca de log 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
- Primavera Web
- Spring Web MVC (Modelo-View-Controller)
- Primavera WebFlux
Dependências para aplicativos nativos do Spring Boot
Métricas
Logs para aplicações nativas do Spring Boot
Para reduzir ou aumentar o número de logs que o Monitor do Azure coleta, primeiro defina o nível de log desejado (como WARNING ou ERROR) na biblioteca de log do aplicativo.
Para aplicações nativas do Quartz, consulte a documentação do Quarkus.
As seguintes bibliotecas de Instrumentação OpenTelemetry estão incluídas como parte da Distro do Azure Monitor Application Insights. Para obter mais informações, consulte SDK do Azure para JavaScript.
Pedidos
Dependências
Registos
Para reduzir ou aumentar o número de logs que o Monitor do Azure coleta, primeiro defina o nível de log desejado (como WARNING ou ERROR) na biblioteca de log do aplicativo.
As instrumentações podem ser configuradas usando 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");
}
}
Pedidos
Dependências
Registos
Para reduzir ou aumentar o número de logs que o Monitor do Azure coleta, primeiro defina o nível de log desejado (como WARNING ou ERROR) na biblioteca de log do aplicativo.
Exemplos de uso da biblioteca de log Python podem ser encontrados no GitHub.
A telemetria emitida pelos SDKs (Software Development Kits) do Azure é coletada automaticamente por padrão.
Notas de rodapé
- ¹: Suporta a comunicação automática de exceções não tratadas/não detetadas
- ²: Suporta métricas OpenTelemetry
Gorjeta
Todas as métricas do OpenTelemetry coletadas automaticamente de bibliotecas de instrumentação ou manualmente coletadas de codificação personalizada são atualmente consideradas "métricas personalizadas" do Application Insights para fins de faturamento.
Mais informações.
Você pode coletar mais dados automaticamente ao incluir bibliotecas de instrumentação da comunidade OpenTelemetry .
Atenção
Não apoiamos nem garantimos a qualidade das bibliotecas de instrumentação comunitárias. Para sugerir um para a nossa distro, publique ou vote na nossa comunidade de feedback. Esteja ciente de que algumas especificações do OpenTelemetry são experimentais e podem introduzir alterações significativas no futuro.
Para adicionar uma biblioteca da comunidade, use os ConfigureOpenTelemetryMeterProvider métodos ou ConfigureOpenTelemetryTracerProvider depois de adicionar o pacote NuGet para a biblioteca.
O exemplo a seguir demonstra como a Instrumentação de Tempo de Execução pode ser adicionada para coletar métricas extras:
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 de Tempo de Execução pode ser adicionada para coletar métricas extras:
// 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();
Não é possível estender a Distro Java com bibliotecas de instrumentação da comunidade. Para solicitar que incluamos outra biblioteca de instrumentação, abra um problema em nossa página do GitHub. Você pode encontrar um link para nossa página do GitHub em Próximas etapas.
Não é possível usar bibliotecas de instrumentação da comunidade com aplicativos nativos 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");
}
}
Para adicionar uma biblioteca de instrumentação da comunidade (não oficialmente suportada/incluída na distribuição do Azure Monitor), pode instrumentar diretamente utilizando os instrumentos. A lista de bibliotecas comunitárias de instrumentação pode ser encontrada aqui.
Nota
Instrumentar manualmente uma biblioteca de instrumentação suportada com instrument() e a distro configure_azure_monitor() não é recomendado. Não é um cenário suportado e você pode obter um comportamento indesejado para 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())
Detetores de recursos
Os detetores de recursos descobrem metadados do ambiente na inicialização e preenchem atributos de recursos do OpenTelemetry como service.name, cloud.providere cloud.resource_id. Esses metadados potencializam experiências no Application Insights, como mapa de aplicativos e vinculação de computação, e melhoram a correlação entre rastreamentos, métricas e logs.
Gorjeta
Os atributos de recurso descrevem o processo e seu ambiente. Os atributos Span descrevem uma única operação. Use atributos de recurso para propriedades no nível do aplicativo, como service.name.
Ambientes suportados
| Meio Ambiente |
Como funciona a deteção |
Observações |
| Serviço de Aplicações do Azure |
O SDK de idioma ou a distro do Azure Monitor lê variáveis de ambiente do Serviço de Aplicativo conhecidas e metadados de host |
Funciona com .NET, Java, Node.jse Python quando você usa as diretrizes neste artigo. |
| Funções do Azure |
Consulte o tutorial do Azure Functions OpenTelemetry |
Todas as orientações para funcionalidades do Azure Functions estão disponíveis lá. |
| Máquinas Virtuais do Azure |
O SDK de idioma ou distro consulta o Serviço de Metadados de Instância do Azure |
Verifique se a VM tem acesso ao ponto de extremidade do Serviço de Metadados de Instância. |
| Serviço Kubernetes do Azure (AKS) |
Use o processador OpenTelemetry Collector k8sattributes para adicionar metadados do Kubernetes |
Recomendado para todos os idiomas em execução no AKS. |
| Azure Container Apps |
Os detetores mapeiam variáveis de ambiente e identificadores de recursos quando disponíveis |
Você também pode definir OTEL_RESOURCE_ATTRIBUTES para preencher lacunas. |
Instrumentação manual e automática
A instrumentação automática e as distribuições do Azure Monitor permitem a deteção de recursos quando executadas em ambientes do Azure onde há suporte.
Para configurações manuais, você pode definir atributos de recursos diretamente com as opções padrão do 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>"
No 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>"
Considerações sobre ingestão de OTLP
- O Application Insights usa
service.name para derivar o nome da função de nuvem. Escolha um nome estável por serviço para evitar nós fragmentados no Mapa de Aplicativos.
-
cloud.resource_id melhora a vinculação de computação aos recursos do Azure. Se esse atributo estiver faltando, algumas experiências podem não mostrar o recurso do Azure que produziu os dados.
Coletar telemetria personalizada
Esta seção explica como coletar telemetria personalizada do seu aplicativo.
Dependendo do seu idioma e tipo de sinal, existem diferentes maneiras de coletar telemetria personalizada, incluindo:
- OpenTelemetry API
- Bibliotecas de logs/métricas adequadas para determinada língua
- API clássica do Application Insights
A tabela a seguir representa os tipos de telemetria personalizada atualmente suportados:
| Linguagem |
Eventos personalizados |
Métricas Personalizadas |
Dependências |
Exceções |
Visualizações de página |
Pedidos |
Rastreios |
|
ASP.NET Núcleo |
|
|
|
|
|
|
|
| OpenTelemetry API |
|
Sim |
Sim |
Sim |
|
Sim |
|
ILogger API (Interface de Programação de Aplicações) |
|
|
|
|
|
|
Sim |
| API clássica AI |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Java |
|
|
|
|
|
|
|
| OpenTelemetry API |
|
Sim |
Sim |
Sim |
|
Sim |
|
Logback, Log4j, JUL |
|
|
|
Sim |
|
|
Sim |
| Métricas do Micrometer |
|
Sim |
|
|
|
|
|
| API clássica AI |
Sim |
Sim |
Sim |
Sim |
Sim |
Sim |
Sim |
|
|
|
|
|
|
|
|
|
Node.js |
|
|
|
|
|
|
|
| OpenTelemetry API |
|
Sim |
Sim |
Sim |
|
Sim |
|
|
|
|
|
|
|
|
|
|
Píton |
|
|
|
|
|
|
|
| OpenTelemetry API |
|
Sim |
Sim |
Sim |
|
Sim |
|
| Módulo de registro em Python |
|
|
|
|
|
|
Sim |
| Extensão de Eventos |
Sim |
|
|
|
|
|
Sim |
Nota
O Application Insights Java 3.x e o Application Insights Node.js 3.x coletam telemetria da API do Application Insights Classic. Esse comportamento simplifica as atualizações e oferece suporte temporário à telemetria personalizada até que a API OpenTelemetry inclua todos os tipos de telemetria personalizada.
Adicionar métricas personalizadas
Nesse contexto, o termo métricas personalizadas refere-se à instrumentação manual do seu código para coletar métricas extras além do que as Bibliotecas de Instrumentação OpenTelemetry coletam automaticamente. Para saber mais sobre como usar métricas, consulte Métricas no Application Insights.
A API 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 métricas no Metrics Explorer. Esse requisito é verdadeiro ao usar a API de métrica 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 OpenTelemetry Metric Instruments.
| Instrumento OpenTelemetry |
Tipo de agregação do Azure Monitor |
| Contador |
Soma |
| Contador assíncrono |
Soma |
| Histograma |
Mín, Máx, Média, Soma e Contagem |
| Medidor assíncrono |
Média |
| UpDownCounter |
Soma |
| UpDownCounter assíncrono |
Soma |
Atenção
Outros tipos de agregação não são significativos na maioria dos casos.
A Especificação OpenTelemetry descreve os instrumentos e fornece exemplos de quando se pode usar cada um.
Gorjeta
O histograma é o mais versátil e mais equivalente à API Classic GetMetric do Application Insights. Atualmente, o Azure Monitor transforma o instrumento de histograma nos cinco tipos de agregação suportados, e o desenvolvimento do suporte a percentis está em andamento. Embora menos versáteis, outros instrumentos OpenTelemetry têm um efeito menor no desempenho do seu aplicativo.
Exemplo de histograma
A inicialização da aplicação deve subscrever-se a um medidor pelo 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 o 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:
Crie 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);
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()
Contraexemplo
A inicialização da aplicação deve subscrever-se a um medidor pelo 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 o 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:
Crie 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"));
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()
Exemplo de medidor
A inicialização da aplicação deve subscrever-se a um medidor pelo 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 o 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:
Crie 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"));
});
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()
Adicionar exceções personalizadas
Selecione bibliotecas de instrumentação que reportam automaticamente exceções ao Application Insights.
No entanto, pode querer reportar manualmente exceções para além do que as bibliotecas de instrumentação reportam.
Por exemplo, as exceções detetadas pelo seu código normalmente não são relatadas. Você pode 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 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 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 uma extensão e registrar exceções.
Adicione opentelemetry-api-1.0.0.jar (ou mais tarde) à sua aplicação:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Defina o estado para error e registe uma exceção no seu 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 estado para error e registe uma exceção no seu 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 SDK do Node.js exporta exceções baseadas em extensão registradas manualmente para o Application Insights como exceções somente quando registradas em uma extensão de nível superior ou em um filho de uma extensão remota ou interna.
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");
}
}
O OpenTelemetry Python SDK é implementado de tal forma que as exceções lançadas são automaticamente capturadas e registradas. Consulte o exemplo de código 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 você quiser registrar exceções manualmente, poderá desabilitar essa opção no gerenciador de contexto e usá-la 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 possas querer adicionar um intervalo personalizado em dois cenários. Primeiro, quando há uma solicitação de dependência ainda não coletada por uma biblioteca de instrumentação. Em segundo lugar, quando se deseja modelar um processo de aplicação como um intervalo na visualização de uma transação completa.
Nota
As Activity classes e ActivitySource do System.Diagnostics namespace representam os conceitos OpenTelemetry de Span e Tracer, respectivamente. Você cria ActivitySource diretamente usando seu construtor em vez de usar TracerProvider. Cada ActivitySource classe deve ser explicitamente conectada a TracerProvider usando AddSource(). Isso ocorre porque partes da API de rastreamento OpenTelemetry são incorporadas diretamente ao tempo de execução do .NET. Para saber mais, consulte 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 define-se por padrão como ActivityKind.Internal, mas podes fornecer qualquer outro ActivityKind.
ActivityKind.Client, ActivityKind.Producere ActivityKind.Internal são mapeados para o Application Insights dependencies.
ActivityKind.Server e ActivityKind.Consumer são mapeados para o Application Insights requests.
Nota
As Activity classes e ActivitySource do System.Diagnostics namespace representam os conceitos OpenTelemetry de Span e Tracer, respectivamente. Você cria ActivitySource diretamente usando seu construtor em vez de usar TracerProvider. Cada ActivitySource classe deve ser explicitamente conectada a TracerProvider usando AddSource(). Isso ocorre porque partes da API de rastreamento OpenTelemetry são incorporadas diretamente ao tempo de execução do .NET. Para saber mais, consulte 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 define-se por padrão como ActivityKind.Internal, mas podes fornecer qualquer outro ActivityKind.
ActivityKind.Client, ActivityKind.Producere ActivityKind.Internal são mapeados para o Application Insights dependencies.
ActivityKind.Server e ActivityKind.Consumer são mapeados para o Application Insights requests.
Usar a anotação OpenTelemetry
A maneira mais simples de adicionar seus próprios spans é usando a @WithSpan anotação do OpenTelemetry.
Os Spans preenchem as requests tabelas e dependencies no Application Insights.
Adicione opentelemetry-instrumentation-annotations-1.32.0.jar (ou mais tarde) à sua aplicação:
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-annotations</artifactId>
<version>1.32.0</version>
</dependency>
Use uma anotação @WithSpan para emitir um intervalo cada vez que o 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 com o tipo de dependência dependenciesInProc.
Para métodos que representam um trabalho em segundo plano não capturado pela autoinstrumentação, recomendamos aplicar o atributo kind = SpanKind.SERVER à anotação @WithSpan para garantir que esses apareçam na tabela do Application Insights requests.
Usar a API OpenTelemetry
Se a anotação OpenTelemetry @WithSpan anterior não satisfizer as suas necessidades, poderá adicionar os seus spans usando a API OpenTelemetry.
Adicione opentelemetry-api-1.0.0.jar (ou mais tarde) à sua aplicação:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Utilize a GlobalOpenTelemetry classe 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 depois termine-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:
Crie um Tracer:
import io.opentelemetry.api.trace.Tracer;
static final Tracer tracer = openTelemetry.getTracer("com.example");
Crie um intervalo, torne-o atual e depois termine-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();
}
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");
}
}
A API OpenTelemetry pode ser usada para adicionar os seus próprios spans, que aparecem nas tabelas requests e dependencies do 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, a extensão está na dependencies tabela com um tipo de dependência de InProc.
Se o seu método representa um trabalho em segundo plano ainda não capturado pela autoinstrumentação, recomendamos definir o atributo kind = SpanKind.SERVER para garantir que ele apareça na tabela do 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.
...
Enviar eventos personalizados
O Application Insights armazena customEvents eventos personalizados na tabela. Uma maneira de analisá-los, filtrá-los e visualizá-los é usando as experiências de uso do Application Insights.
Se quiser automatizar a coleção de eventos de interação do lado do cliente, você pode usar o plug-in no JavaScript SDK.
Os eventos personalizados estão na Pré-visualização Pública e utilizam Azure.Monitor.OpenTelemetry.AspNetCore 1.3.0-beta.3.
Para enviar um CustomEvent usando ILogger, defina o "microsoft.custom_event.name" atributo 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 na Pré-visualização Pública e utilizam Azure.Monitor.OpenTelemetry.Exporter 1.4.0-beta.3.
Para enviar um CustomEvent usando ILogger, defina o "microsoft.custom_event.name" atributo 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 registo de log 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 OpenTelemetry é ligeiramente diferente. Este detalhe é explicado mais detalhadamente 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 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 suportam anexar ou analisar o atributo de eventos personalizados.
Não é possível enviar um customEvent usando o "microsoft.custom_event.name" atributo em Java nativo.
Para enviar um customEvent utilizando logger.emit, defina o atributo "microsoft.custom_event.name" no objeto de log attributes. Outros atributos também podem ser incluídos conforme necessário.
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");
}
}
Para enviar um customEvent em Python, use a biblioteca de logging 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 span
Esses atributos podem incluir a adição de uma propriedade personalizada à sua 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 às extensões são exportados como propriedades personalizadas. Eles preenchem o campo customDimensions na tabela de solicitações, dependências, rastreamentos ou exceções.
Para adicionar atributos span, use uma das duas maneiras a seguir:
- Use as opções fornecidas pelas bibliotecas de instrumentação.
- Adicione um processador span personalizado.
Gorjeta
A vantagem de usar as opções fornecidas pelas bibliotecas de instrumentação, quando estão disponíveis, é que todo o contexto está disponível. Como resultado, os usuários podem optar por adicionar ou filtrar mais atributos. Por exemplo, a opção enrich na biblioteca de instrumentação HttpClient dá aos usuários acesso ao HttpRequestMessage e ao próprio HttpResponseMessage. Eles podem selecionar qualquer coisa dele e armazená-lo como um atributo.
Muitas bibliotecas de instrumentação oferecem uma opção enriquecedora. Para obter orientação, consulte os arquivos readme de bibliotecas de instrumentação individuais:
Use um processador personalizado:
Gorjeta
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 span, use uma das duas maneiras a seguir:
- Utilize as opções fornecidas pelas bibliotecas de instrumentação.
- Adicione um processador span personalizado.
Gorjeta
A vantagem de usar as opções fornecidas pelas bibliotecas de instrumentação, quando estão disponíveis, é que todo o contexto está disponível. Como resultado, os usuários podem optar por adicionar ou filtrar mais atributos. Por exemplo, a opção de enriquecimento na biblioteca de instrumentação HttpClient dá aos utilizadores acesso ao próprio httpRequestMessage. Eles podem selecionar qualquer coisa dele e armazená-lo como um atributo.
Muitas bibliotecas de instrumentação oferecem uma opção enriquecedora. Para obter orientação, consulte os arquivos readme de bibliotecas de instrumentação individuais:
Use um processador personalizado:
Gorjeta
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 spans.
Adicionar um ou mais atributos span preenche o customDimensions campo na requests, dependencies, traces ou exceptions tabela.
Adicione opentelemetry-api-1.0.0.jar (ou mais tarde) à sua aplicação:
<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");
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");
}
}
Use 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 para solicitações definindo um atributo na extensão. O Application Insights usa o endereço IP para gerar atributos de localização do usuário e, em seguida, descarta-o 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 este campo.
Este campo é preenchido automaticamente.
Use o exemplo de propriedade personalizada, mas substitua as seguintes linhas de código:
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.");
}
}
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 o ID de usuário ou o ID de usuário autenticado
Você pode preencher o campo user_Id ou user_AuthenticatedId para solicitações usando as diretrizes a seguir. O ID de utilizador é um identificador de utilizador anónimo. ID de usuário autenticado é um identificador de usuário conhecido.
Importante
Consulte as leis de privacidade aplicáveis antes de definir o ID de Usuário Autenticado.
Preencha o campo user ID na tabela requests, dependencies ou exceptions.
Adicione opentelemetry-api-1.0.0.jar (ou mais tarde) à sua aplicação:
<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"); // (user_AuthenticatedId)
Span.current().setAttribute("enduser.pseudo.id", "myuser"); // (user_Id)
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"); // (user_AuthenticatedId)
Span.current().setAttribute("enduser.pseudo.id", "myuser"); // (user_Id)
Use o exemplo de propriedade personalizada, mas substitua as seguintes linhas de código:
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.");
}
}
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's ILogger.
A anexação de dimensões personalizadas aos logs pode ser realizada usando um modelo de mensagem.
OpenTelemetry usa . NET's ILogger.
A anexação de dimensões personalizadas aos logs pode ser realizada usando um modelo de mensagem.
Logback, Log4j e java.util.logging são instrumentados automaticamente. A anexação de dimensões personalizadas aos seus logs pode ser realizada das seguintes maneiras:
Para aplicações nativas do Spring Boot, o Logback vem pré-configurado.
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");
}
}
A biblioteca de log Python é autoinstrumentada. Você pode atribuir dimensões personalizadas aos seus logs passando um dicionário no argumento extra dos 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 trace ID ou span ID
Você pode obter o Trace ID e Span ID do Span atualmente ativo usando as etapas a seguir.
Nota
As Activity classes e ActivitySource do System.Diagnostics namespace representam os conceitos OpenTelemetry de Span e Tracer, respectivamente. Isso ocorre porque partes da API de rastreamento OpenTelemetry são incorporadas diretamente ao tempo de execução do .NET. Para saber mais, consulte 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();
Nota
As Activity classes e ActivitySource do System.Diagnostics namespace representam os conceitos OpenTelemetry de Span e Tracer, respectivamente. Isso ocorre porque partes da API de rastreamento OpenTelemetry são incorporadas diretamente ao tempo de execução do .NET. Para saber mais, consulte 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 de traço ou o ID de intervalo.
Adicione opentelemetry-api-1.0.0.jar (ou mais tarde) à sua aplicação:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>1.0.0</version>
</dependency>
Obtenha o ID de rastreamento de solicitação e o ID de span em 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 de solicitação e o ID de span em 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 de solicitação e o ID de span em seu código:
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);
}
}
Obtenha o ID de rastreamento de solicitação e o ID de span em 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óximos passos
- Para configurar ainda mais a distro OpenTelemetry , consulte Configuração do Azure Monitor OpenTelemetry .
- Para revisar o código-fonte, consulte o repositório GitHub do Azure Monitor AspNetCore.
- Para instalar o pacote NuGet, verificar se há atualizações ou exibir notas de versão, consulte a página Pacote NuGet do Azure Monitor AspNetCore.
- Para se familiarizar com o Azure Monitor e o OpenTelemetry, consulte o Aplicativo de exemplo do Azure Monitor.
- Para saber mais sobre o OpenTelemetry e sua comunidade, consulte o repositório OpenTelemetry .NET GitHub.
- Para habilitar experiências de uso, habilite o monitoramento de usuários da Web ou do navegador.
- Para revisar perguntas frequentes, etapas de solução de problemas, opções de suporte ou fornecer comentários sobre o OpenTelemetria, consulte Ajuda, suporte e comentários do OpenTelemetry para o Azure Monitor Application Insights.
- Para configurar ainda mais a distro OpenTelemetria, consulte Configuração do Azure Monitor OpenTelemetry
- Para rever o código-fonte, consulte o repositório GitHub do Exportador Azure Monitor.
- Para instalar o pacote NuGet, verificar se há atualizações ou consultar as notas de versão, veja a página do Pacote NuGet do Exportador do Azure Monitor.
- Para se familiarizar com o Azure Monitor e o OpenTelemetry, consulte o Aplicativo de exemplo do Azure Monitor.
- Para saber mais sobre o OpenTelemetry e sua comunidade, consulte o repositório OpenTelemetry .NET GitHub.
- Para habilitar experiências de uso, habilite o monitoramento de usuários da Web ou do navegador.
- Para revisar perguntas frequentes, etapas de solução de problemas, opções de suporte ou fornecer comentários sobre o OpenTelemetria, consulte Ajuda, suporte e comentários do OpenTelemetry para o Azure Monitor Application Insights.
- Para revisar o código-fonte, consulte o repositório GitHub do Azure Monitor OpenTelemetry .
- Para instalar o pacote npm e verificar se há atualizações, consulte a página Pacote
@azure/monitor-opentelemetry
- Para se familiarizar com o Azure Monitor Application Insights e o OpenTelemetry, consulte o Aplicativo de exemplo do Azure Monitor.
- Para saber mais sobre o OpenTelemetry e sua comunidade, consulte o repositório OpenTelemetry JavaScript GitHub.
- Para habilitar experiências de uso, habilite o monitoramento de usuários da Web ou do navegador.
- Para revisar perguntas frequentes, etapas de solução de problemas, opções de suporte ou fornecer comentários sobre o OpenTelemetria, consulte Ajuda, suporte e comentários do OpenTelemetry para o Azure Monitor Application Insights.
- Para revisar o código-fonte e a documentação extra, consulte o repositório GitHub do Azure Monitor Distro.
- Para ver exemplos e casos de uso extras, consulte Exemplos de Distro do Azure Monitor.
- Para ver as notas de versão, consulte as notas de versão no GitHub.
- Para instalar o pacote PyPI, verificar se há atualizações ou exibir notas de versão, consulte a página Azure Monitor Distro PyPI Package .
- Para se familiarizar com o Azure Monitor Application Insights e o OpenTelemetry, consulte o Aplicativo de exemplo do Azure Monitor.
- Para saber mais sobre o OpenTelemetry e sua comunidade, consulte o repositório OpenTelemetry Python GitHub.
- Para ver as instrumentações e componentes OpenTelemetry disponíveis, consulte o repositório Python GitHub do OpenTelemetry Contributor.
- Para habilitar experiências de uso, habilite o monitoramento de usuários da Web ou do navegador.
- Para revisar perguntas frequentes, etapas de solução de problemas, opções de suporte ou fornecer comentários sobre o OpenTelemetria, consulte Ajuda, suporte e comentários do OpenTelemetry para o Azure Monitor Application Insights.