你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:使用 Azure OpenTelemetry 导出程序将 SDK 遥测数据导出到 Application Insights

Azure OpenTelemetry 导出程序是 Azure Monitor 中的 SDK。 通过此导出程序,可以使用 OpenTelemetry 导出跟踪数据并将数据发送到 Application Insights。 OpenTelemetry 为应用程序和框架提供了一种标准化方法来收集遥测信息。

Azure Application Insights 是用于监视实时应用程序的 Azure Monitor 的一项功能。 这一功能可显示关于 Microsoft Azure 资源中应用程序的遥测数据。 标准化遥测模型可以创建不依赖于平台和语言的监测。

先决条件

设置

新建 C# 应用程序

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,使用 dotnet new 命令创建名为 TelemetryAppInsightsQuickstart 的新控制台应用。 此命令将创建包含单个源文件的简单“Hello World”C# 项目:Program.cs

dotnet new console -o TelemetryAppInsightsQuickstart

将目录更改为新创建的应用文件夹,并使用 dotnet build 命令编译应用程序。

cd TelemetryAppInsightsQuickstart
dotnet build

安装包

仍在应用程序目录中时,使用 dotnet add package 命令安装适用于 .NET 包的 Azure 通信服务标识库。

dotnet add package Azure.Communication.Identity --version 1.0.0

还需要安装 Azure Monitor Exporter for OpenTelemetry 库。

dotnet add package Azure.Monitor.OpenTelemetry.Exporter -v 1.0.0-beta.3

设置应用框架

从项目目录中执行以下操作:

  1. 在文本编辑器中打开 Program.cs 文件
  2. 添加 using 指令以包括 Azure.Communication.Identity 命名空间
  3. 添加 using 指令以包括 Azure.Monitor.OpenTelemetry.Exporter 命名空间;
  4. 添加 using 指令以包括 OpenTelemetry.Trace 命名空间;
  5. 更新 Main 方法声明以支持异步代码

使用以下代码以开始执行以下操作:

using System;
using System.Diagnostics;
using Azure.Communication;
using Azure.Communication.Identity;
using Azure.Monitor.OpenTelemetry.Exporter;
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

namespace TelemetryAppInsightsQuickstart
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Azure Communication Services - Export Telemetry to Application Insights");

            // Quickstart code goes here
        }
    }
}

通过调用通信标识 SDK 设置遥测跟踪器

使用连接字符串初始化 CommunicationIdentityClient。 了解如何管理资源的连接字符串

创建客户端后,必须定义一个 Activity Source 来跟踪所有活动。 然后,你可以使用 Activity Source 来启动 Activity,后者将用于跟踪 CreateUserAsync SDK 调用。 请注意,还可以使用 SetTag 方法定义要在每个 Activity 中跟踪的自定义属性。

将为 GetTokenAsync 函数执行类似的跟踪模式。

创建一个名为 TracedSample 的新函数并添加以下代码:

public static async Task TracedSample()
{
    // This code demonstrates how to fetch your connection string
    // from an environment variable.
    string connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");
    var client = new CommunicationIdentityClient(connectionString);

    using var source = new ActivitySource("Quickstart.IdentityTelemetry");
    CommunicationUserIdentifier identity = null;

    using (var activity = source.StartActivity("Create User Activity"))
    {
        var identityResponse = await client.CreateUserAsync();

        identity = identityResponse.Value;
        Console.WriteLine($"\nCreated an identity with ID: {identity.Id}");
        activity?.SetTag("Identity id", identity.Id);
    }

    using (var activity = source.StartActivity("Get Token Activity"))
    {
        var tokenResponse = await client.GetTokenAsync(identity, scopes: new[] { CommunicationTokenScope.Chat });

        activity?.SetTag("Token value", tokenResponse.Value.Token);
        activity?.SetTag("Expires on", tokenResponse.Value.ExpiresOn);

        Console.WriteLine($"\nIssued an access token with 'chat' scope that expires at {tokenResponse.Value.ExpiresOn}:");
    }
}

将遥测数据汇集到 Application Insights

SDK 调用与活动包装在一起后,你可以添加 OpenTelemetry 跟踪导出程序,并将数据汇集到 Application Insights 资源中。

可以选择使用某些资源属性定义字典,这些属性将显示在 Application Insights 中。 然后调用 AddSource,并使用在 TracedSample 中定义的同一个“活动源”名称。 还需要从 Application Insights 资源中获取连接字符串,并将其传递给 AddAzureMonitorTraceExporter()。 这会将遥测数据汇集到 Application Insights 资源。

最后,调用并等待包含我们的 SDK 调用的 TracedSample() 函数。

将以下代码添加到 Main 方法中:

var resourceAttributes = new Dictionary<string, object> { { "service.name", "<service-name>" }, { "service.instance.id", "<service-instance-id>" } };
var resourceBuilder = ResourceBuilder.CreateDefault().AddAttributes(resourceAttributes);

using var tracerProvider = Sdk.CreateTracerProviderBuilder()
    .SetResourceBuilder(resourceBuilder)
    .AddSource("Quickstart.IdentityTelemetry")
    .AddAzureMonitorTraceExporter(o =>
    {
        o.ConnectionString = Environment.GetEnvironmentVariable("APPLICATION_INSIGHTS_CONNECTION_STRING");
    })
    .Build();

await TracedSample();

运行代码

从应用程序目录使用 dotnet run 命令运行应用程序。

dotnet run

先决条件

设置

新建 Node.js 应用

如果你已经有一个使用 Azure 通信服务库的应用并且能够熟练操作 JavaScript,可以跳转到设置跟踪程序

若要开始,需要准备好一个使用我们任一客户端库的 JS 应用。 我们将使用 @azure/communication-identity 库来创建应用。 按照以下步骤设置示例应用:

打开终端或命令窗口,创建一个新目录,并导航到该目录。

mkdir export-js-telemetry && cd export-js-telemetry

运行 npm init -y 以使用默认设置创建 package.json。

npm init -y

安装依赖项

使用 npm install 命令安装应用将要使用的依赖项。

npm install @azure/communication-identity @azure/monitor-opentelemetry-exporter @opentelemetry/node@^0.14.0 @opentelemetry/plugins-node-core --save

--save 选项将库添加为上一步骤创建的 package.json 文件中的依赖项。

请务必不要忘记 @opentelemetry/node@^0.14.0 的具体版本。 在编写本指南时,它是该包的最新版本,与 @azure/monitor-opentelemetry-exporter 完全兼容。

添加主应用文件

在根目录中创建名为 token.js 的文件。 向新文件添加以下代码:

// token.js

const { CommunicationIdentityClient } = require("@azure/communication-identity");

async function main() {
  const ACS_CONNECTION_STRING = "<your-acs-connection-string>"
  const client = new CommunicationIdentityClient(ACS_CONNECTION_STRING);

  console.log("Creating user...")
  const user = await client.createUser();
  console.log(`User ${user.communicationUserId} was created successfully.\n`);

  console.log(`Issuing token for ${user.communicationUserId}...`);
  const { token } = await client.getToken(user, ["chat"]);
  console.log("Token issued successfully.\n")
  console.log(`${token}\n`);

  console.log(`Revoking token for ${user.communicationUserId}...`);
  await client.revokeTokens(user);
  console.log("Token revoked successfully.\n");

  console.log(`Deleting user ${user.communicationUserId}...`);
  await client.deleteUser(user);
  console.log("User deleted successfully.\n");
}

main().catch((error) => {
  console.log("Encountered an error:", error);
  process.exit(1);
});

设置跟踪程序

在根目录中创建名为 tracing.js 的文件。 向新文件添加以下代码:

// tracing.js

const azureSdkTracing = require("@azure/core-tracing");
const { AzureMonitorTraceExporter } = require("@azure/monitor-opentelemetry-exporter");
const { NodeTracerProvider } = require("@opentelemetry/node");
const { BatchSpanProcessor } = require("@opentelemetry/tracing");

const AI_CONNECTION_STRING = "<your-application-insights-connection-string>";
const provider = new NodeTracerProvider();
const azExporter = new AzureMonitorTraceExporter({
  connectionString: AI_CONNECTION_STRING
});

provider.addSpanProcessor(
  new BatchSpanProcessor(azExporter, {
    bufferSize: 1000, // 1000 spans
    bufferTimeout: 5000 // 5 seconds
  })
);

provider.register();

const tracer = provider.getTracer("sample tracer");
azureSdkTracing.setTracer(tracer);

exports.default = tracer;

将跟踪程序添加到主应用

对 token.js 进行以下更新:

需要 tracing.js:

const { CommunicationIdentityClient } = require("@azure/communication-identity");
const tracer = require("./tracing.js");

async function main() {

创建根范围并导出数据

  console.log("User deleted successfully.\n");
}

const rootSpan = tracer.startSpan("Root Identity Span");
tracer.withSpan(rootSpan, async function() {
  try {
    await main();
  } catch (error) {
    console.error("Error running sample:", error);
  } finally {
    // End the optional root span on completion
    rootSpan.end();
  }
}).then(function() {
  console.log("Awaiting batched span processor to export batched spans...");

  setTimeout(function() {
    console.log("Spans exported.");
  }, 6000);
});

运行代码

请务必将占位符文本替换为有效的连接字符串值。

使用 node 命令运行添加到 token.js 文件中的代码。

node token.js

先决条件

设置

创建新的 Java 应用程序

打开终端或命令窗口。 导航到要在其中创建 Java 应用程序的目录。 运行以下命令以从 maven-archetype-quickstart 模板生成 Java 项目。

mvn archetype:generate -DgroupId=com.communication.quickstart -DartifactId=communication-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

你会注意到,“生成”任务创建了与 artifactId 名称相同的目录。 在此目录下,src/main/java 目录包含项目源代码,src/test/java directory 包含测试源,pom.xml 文件是项目的项目对象模型 (POM)。

安装包

在文本编辑器中打开 pom.xml 文件。 将以下依赖项元素添加到依赖项组。

    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-communication-identity</artifactId>
      <version>1.0.0</version>
    </dependency>
    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-monitor-opentelemetry-exporter</artifactId>
      <version>1.0.0-beta.4</version>
    </dependency>

设置应用框架

从项目目录中执行以下操作:

  1. 导航到 /src/main/java/com/communication/quickstart 目录
  2. 在编辑器中打开 App.java 文件
  3. 替换 System.out.println("Hello world!"); 语句
  4. 添加 import 指令

使用以下代码以开始执行以下操作:

package com.communication.quickstart;

import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
import com.azure.monitor.opentelemetry.exporter.*;
import com.azure.communication.identity.*;

public class App
{
    public static void main( String[] args ) throws Exception
    {
        System.out.println("Azure Communication Services - Export Telemetry to Application Insights");
        // Quickstart code goes here
    }
}

通过调用通信标识 SDK 设置遥测跟踪器

使用连接字符串初始化 CommunicationIdentityClient。 了解如何管理资源的连接字符串


    CommunicationIdentityClient client = new CommunicationIdentityClientBuilder()
        .connectionString("<COMMUNICATION-RESOURCE-CONNECTION-STRING>")
        .buildClient();

首先,若要创建用于在 Azure Monitor 中跟踪请求的 span,必须创建一个 AzureMonitorTraceExporter 对象实例。 你需要提供 Application Insights 资源的连接字符串

    AzureMonitorTraceExporter exporter = new AzureMonitorExporterBuilder()
        .connectionString("<APPLICATION-INSIGHTS-CONNECTION-STRING>")
        .buildTraceExporter();

然后,此导出程序会允许你创建以下实例,以便进行请求跟踪。 创建 AzureMonitorTraceExporter 之后添加以下代码:


    SdkTracerProvider tracerProvider = SdkTracerProvider.builder()
        .addSpanProcessor(SimpleSpanProcessor.create(exporter))
        .build();

    OpenTelemetrySdk openTelemetrySdk = OpenTelemetrySdk.builder()
        .setTracerProvider(tracerProvider)
        .buildAndRegisterGlobal();

    Tracer tracer = openTelemetrySdk.getTracer("Sample");

初始化跟踪器后,便可以创建将负责跟踪请求的 span。

    Span span = tracer.spanBuilder("sample-span").startSpan();
    final Scope scope = span.makeCurrent();
    try {
        // Thread bound (sync) calls will automatically pick up the parent span and you don't need to pass it explicitly.
        client.createUser();
    } finally {
        span.end();
        scope.close();
    }
    Thread.sleep(10000);

运行代码

导航到包含 pom.xml 文件的目录,并使用以下 mvn 命令编译该项目。

mvn compile

然后,生成包。

mvn package

运行以下 mvn 命令以执行应用。

mvn exec:java -Dexec.mainClass="com.communication.quickstart.App" -Dexec.cleanupDaemonThreads=false

先决条件

设置

创建新的 Python 应用程序

  1. 打开终端或命令窗口,为应用创建一个新目录,并导航到该目录。

    mkdir application-insights-quickstart && cd application-insights-quickstart
    
  2. 使用文本编辑器在项目根目录中创建一个名为“application-insights-quickstart.py”的文件,并添加程序的结构,包括基本异常处理。 将在以下部分中将此快速入门的所有源代码添加到此文件。

     import os
     from opentelemetry import trace
     from opentelemetry.sdk.trace import TracerProvider
     from opentelemetry.sdk.trace.export import BatchSpanProcessor
     from azure.communication.identity import CommunicationIdentityClient, CommunicationUserIdentifier
    
     from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
    
    try:
       print("Azure Communication Services - Access Tokens Quickstart")
       # Quickstart code goes here
    except Exception as ex:
       print("Exception:")
       print(ex)
    

安装包

仍在应用程序目录中时,安装适用于 Python 包的 Azure 通信服务标识 SDK 和适用于 Azure Monitor 的 Microsoft Opentelemetry Exporter。

pip install azure-communication-identity
pip install azure-monitor-opentelemetry-exporter --pre

通过调用通信标识 SDK 设置遥测跟踪器

使用连接字符串实例化 CommunicationIdentityClient。 下面的代码从名为 COMMUNICATION_SERVICES_CONNECTION_STRING 的环境变量中检索资源的连接字符串。 了解如何管理资源的连接字符串

try 块内添加此代码:

connection_string = os.environ["COMMUNICATION_SERVICES_CONNECTION_STRING"]
identity_client = CommunicationIdentityClient.from_connection_string(connection_string)

首先,若要创建用于在 Azure Monitor 中跟踪请求的 span,必须创建一个 AzureMonitorTraceExporter 对象实例。 你需要提供 Application Insights 资源的连接字符串

exporter = AzureMonitorTraceExporter.from_connection_string(
    "<APPLICATION-INSIGHTS-RESOURCE-CONNECTION-STRING>"
)

然后,此导出程序会允许你创建以下实例,以便进行请求跟踪。 创建 AzureMonitorTraceExporter 之后添加以下代码:

    trace.set_tracer_provider(TracerProvider())
    tracer = trace.get_tracer(__name__)
    span_processor = BatchSpanProcessor(exporter)
    trace.get_tracer_provider().add_span_processor(span_processor)

初始化跟踪器后,便可以创建将负责跟踪请求的 span。

with tracer.start_as_current_span(name="MyIdentityApplication"):
    user = identity_client.create_user()

运行代码

从控制台提示符导航到包含 application-insights-quickstart.py 文件的目录,然后执行以下 python 命令来运行应用。

python application-insights-quickstart.py

应用的输出描述每个已完成的操作:

Created an identity with ID: <identity-id>
Issued an access token with 'chat' scope that expires at <expiry-data>

在 Application Insights 中查看遥测数据

若要从 SDK 分析遥测数据,请转到 Performance 选项卡,然后转到 Dependencies。 你将看到我们已经跟踪的 Create User ActivityGet Token Activity

显示 Application Insights 中遥测数据条目的屏幕截图。

若要查看更多详细信息,可以深入了解这些示例:

显示示例的向下钻取视图的屏幕截图

在向下钻取视图中,包含有关活动的详细信息,例如从何处调用活动、活动的时间戳、名称、性能、类型等。你还可以查看在上面的示例代码段中定义的云角色名称和实例 ID。 请注意,所跟踪的自定义属性也会显示在此处:

事务详细信息的端到端视图

后续步骤

在此快速入门中,读者学习了如何:

  • 设置遥测导出程序
  • 将遥测数据汇集到 Application Insights
  • 查看 Application Insights 中的导出数据

你可能还想要: