为 Node.js 应用程序中的特性标志启用遥测

在本教程中,你将在 Node.js 应用程序中使用遥测来跟踪功能标志评估和自定义事件。 遥测允许你对功能管理策略做出明智的决策。 你在概述中创建了启用遥测的特性标志,并使用这些特性标志来启用遥测功能。 在继续作之前,请确保在配置存储中创建一个名为 Greeting 的功能标志,并启用遥测。 本教程以教程在 Node.js 应用程序中使用变体功能标志为基础进行扩展。

先决条件

将遥测添加到 Node.js 应用程序

  1. 安装以下包。

    npm install @microsoft/feature-management-applicationinsights-node
    
  2. 打开 server.js 并添加以下代码,以连接到 Application Insights 以发布遥测数据。

    const appInsightsConnectionString = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING;
    const applicationInsights = require("applicationinsights");
    applicationInsights.setup(appInsightsConnectionString).start();
    
    const express = require("express");
    const server = express();
    // existing code ...
    
  3. 添加以下导入。

    const { createTelemetryPublisher, trackEvent } = require("@microsoft/feature-management-applicationinsights-node");
    
  4. 初始化 FeatureManager 时创建和注册遥测发布程序。

    // existing code ...
    const featureFlagProvider = new ConfigurationMapFeatureFlagProvider(appConfig);
    const publishTelemetry = createTelemetryPublisher(applicationInsights.defaultClient);
    featureManager = new FeatureManager(featureFlagProvider, {
        onFeatureEvaluated: publishTelemetry
    });
    // existing code ...
    

    每次评估功能标志时,publishTelemetry 回调都会发送遥测数据。

  5. 跟踪用户交互的自定义事件。 将/api/like终结点修改为每当用户喜欢内容时发送遥测数据到 Application Insights。 这有助于分析哪些功能变体的性能更好。

    server.post("/api/like", (req, res) => {
        const { UserId } = req.body;
        if (UserId === undefined) {
            return res.status(400).send({ error: "UserId is required" });
        }
        trackEvent(applicationInsights.defaultClient, UserId, { name: "Liked" });
        res.status(200).send();
    });
    

运行应用程序

  1. Application Insights 需要连接字符串才能连接到 Application Insights 资源。 将 APPLICATIONINSIGHTS_CONNECTION_STRING 环境变量设置为 Application Insights 资源的连接字符串。

    setx APPLICATIONINSIGHTS_CONNECTION_STRING "applicationinsights-connection-string"
    

    如果使用 PowerShell,请运行以下命令:

    $Env:APPLICATIONINSIGHTS_CONNECTION_STRING = "applicationinsights-connection-string"
    

    如果使用 macOS 或 Linux,则请运行以下命令:

    export APPLICATIONINSIGHTS_CONNECTION_STRING='applicationinsights-connection-string'
    

收集遥测数据

部署应用程序以开始从用户收集遥测数据。 若要测试其功能,可以通过创建多个测试用户来模拟用户活动。 每个用户将体验不同的问候消息变体,他们可以通过单击心脏按钮来与应用程序交互,以像报价一样。 随着用户群的增长,可以监视 Azure 应用配置中收集的遥测数据量增加。 此外,还可以向下钻取到数据,以分析功能标志的每个变体如何影响用户行为。

其他资源