快速入门:使用 Azure Application Insights 开始监视 Node.js Web 应用程序Quickstart: Start monitoring your Node.js Web application with Azure Application Insights

在本快速入门中,会将用于 Node.js 的 Application Insights SDK 版本 0.22 添加到现有 Node.js Web 应用程序中。In this quickstart, you add the Application Insights SDK version 0.22 for Node.js to an existing Node.js web application.

使用 Azure Application Insights,可轻松监视 Web 应用程序的可用性、性能和使用情况。With Azure Application Insights, you can easily monitor your web application for availability, performance, and usage. 还可以快速确定并诊断应用程序中的错误,而无需等待用户报告这些错误。You can also quickly identify and diagnose errors in your application without waiting for a user to report them. 使用 0.20 版 SDK 发行版及更高版本,可以监视常见的第三方包,包括 MongoDB、MySQL 和 Redis。With the version 0.20 SDK release onward, you can monitor common third-party packages, including MongoDB, MySQL, and Redis.

先决条件Prerequisites

启用 Application InsightsEnable Application Insights

无论是在本地运行还是在云中运行,Application Insights 都可以从任何与 Internet 连接的应用程序中收集遥测数据。Application Insights can gather telemetry data from any internet-connected application, whether or not it's running on-premises or in the cloud. 按照以下步骤开始查看此数据。Use the following steps to start viewing this data.

  1. 登录 Azure 门户Sign in to the Azure portal.

  2. 选择“创建资源” > “开发人员工具” > “Application Insights”。Select Create a resource > Developer tools > Application Insights.

    添加 Azure Application Insights 资源

    备注

    如果这是你首次创建 Application Insights 资源,可以通过访问创建 Application Insights 资源文档来了解更多信息。If this is your first time creating an Application Insights resource you can learn more by visiting the Create an Application Insights Resource doc.

    此时会显示配置页,请使用下表填写输入字段。A configuration page appears; use the following table to fill out the input fields.

    设置Settings Value 说明Description
    名称Name 全局唯一值Globally Unique Value 标识所监视的应用的名称Name that identifies the app you're monitoring
    资源组Resource Group myResourceGroupmyResourceGroup 用于托管 AppInsights 数据的新资源组的名称。Name for the new resource group to host AppInsights data. 可创建新的资源组或使用现有资源组。You can create a new resource group or use an existing one.
    位置Location 中国东部 2China East2 选择离你近的位置或离托管应用的位置近的位置Choose a location near you, or near where your app is hosted
  3. 选择“创建” 。Select Create.

配置 AppInsights SDKConfigure AppInsights SDK

  1. 选择“概述”,然后复制应用程序的 检测密钥Select Overview and copy your application's Instrumentation Key.

    查看 Application Insights 检测密钥

  2. 将用于 Node.js 的 Application Insights SDK 添加到应用程序。Add the Application Insights SDK for Node.js to your application. 从应用的根文件夹运行:From your app's root folder run:

    npm install applicationinsights --save
    
  3. 编辑应用的第一个 .js 文件并将以下两行添加到脚本的最顶部。Edit your app's first .js file and add the two lines below to the topmost part of your script. 如果使用的是 Node.js 快速入门应用,则将修改 index.js 文件。If you're using the Node.js quickstart app, you would modify the index.js file. <instrumentation_key> 替换为应用程序见解的检测密钥。Replace <instrumentation_key> with your application insight's instrumentation key.

    const appInsights = require('applicationinsights');
    appInsights.setup('<instrumentation_key>').start();
    
  4. 重启应用。Restart your app.

备注

这需要 3-5 分钟,然后数据才开始显示在门户中。It takes 3-5 minutes before data begins appearing in the portal. 如果此应用是一个低流量测试应用,请记住,仅当存在活动请求或正在执行的操作时,才会捕获大多数指标。If this app is a low-traffic test app, keep in mind that most metrics are only captured when there are active requests or operations occurring.

开始在 Azure 门户中监视Start monitoring in the Azure portal

  1. 现在可以在 Azure 门户中重新打开 Application Insights“概述” 页(已在其中检索到检测密钥),查看有关当前正在运行的应用程序的详细信息。You can now reopen the Application Insights Overview page in the Azure portal, where you retrieved your instrumentation key, to view details about your currently running application.

    Application Insights“概述”菜单

  2. 选择“应用程序映射” 以获取应用程序组件之间依赖关系的可视布局。Select Application map for a visual layout of the dependency relationships between your application components. 每个组件均显示 KPI,如负载、性能、失败和警报。Each component shows KPIs such as load, performance, failures, and alerts.

    Application Insights 应用程序映射

  3. 选择“应用分析” 图标 “应用程序映射”图标 “在 Analytics 中查看”。Select the App Analytics icon Application Map icon View in Analytics. 此操作将打开“Application Insights Analytics” ,该扩展提供丰富的查询语言,用于分析 Application Insights 收集的所有数据。This action opens Application Insights Analytics, which provides a rich query language for analyzing all data collected by Application Insights. 在本示例中,将生成以图表形式呈现请求计数的查询。In this case, a query is generated for you that renders the request count as a chart. 可以编写自己的查询来分析其他数据。You can write your own queries to analyze other data.

    Application Insights Analytics 图形

  4. 返回到“概述” 页并检查 KPI 图形。Return to the Overview page and examine the KPI graphs. 此仪表板提供有关应用程序运行状况的统计信息,包括传入请求数、这些请求的持续时间,以及发生的任何故障。This dashboard provides statistics about your application health, including the number of incoming requests, the duration of those requests, and any failures that occur.

    Application Insights“运行状况概述时间线”图

    若要启用“页面视图加载时间” 图表以填充“客户端遥测” 数据,请将此脚本添加到要跟踪的每一页:To enable the Page View Load Time chart to populate with client-side telemetry data, add this script to each page that you want to track:

    <!-- 
    To collect user behavior analytics tools about your application, 
    insert the following script into each page you want to track.
    Place this code immediately before the closing </head> tag,
    and before any other scripts. Your first data will appear 
    automatically in just a few seconds.
    -->
    <script type="text/javascript">
      var appInsights=window.appInsights||function(config){
        function i(config){t[config]=function(){var i=arguments;t.queue.push(function(){t[config].apply(t,i)})}}var t={config:config},u=document,e=window,o="script",s="AuthenticatedUserContext",h="start",c="stop",l="Track",a=l+"Event",v=l+"Page",y=u.createElement(o),r,f;y.src=config.url||"https://az416426.vo.msecnd.net/scripts/a/ai.0.js";u.getElementsByTagName(o)[0].parentNode.appendChild(y);try{t.cookie=u.cookie}catch(p){}for(t.queue=[],t.version="1.0",r=["Event","Exception","Metric","PageView","Trace","Dependency"];r.length;)i("track"+r.pop());return i("set"+s),i("clear"+s),i(h+a),i(c+a),i(h+v),i(c+v),i("flush"),config.disableExceptionTracking||(r="onerror",i("_"+r),f=e[r],e[r]=function(config,i,u,e,o){var s=f&&f(config,i,u,e,o);return s!==!0&&t["_"+r](config,i,u,e,o),s}),t
        }({
            instrumentationKey:"<insert instrumentation key>"
        });
    
        window.appInsights=appInsights;
        appInsights.trackPageView();
    </script>
    
  5. 在左侧,选择“指标”。 On the left, select Metrics. 使用指标资源管理器调查资源的运行状况和利用率。Use the metrics explorer to investigate the health and utilization of your resource. 可以选择“添加新图表” 创建其他自定义视图,或者选择“编辑” 修改现有的图表类型、高度、调色板、分组和指标。You can select Add new chart to create additional custom views or select Edit to modify the existing chart types, height, color palette, groupings, and metrics. 例如,可以制作一个图表来显示浏览器页面的平均加载时间,只需从指标下拉列表中选择“浏览器页面加载时间”并从聚合中选择“平均”即可。For example, you can make a chart that displays the average browser page load time by selecting "Browser page load time" from the metrics drop down and "Avg" from aggregation. 若要详细了解 Azure 指标资源管理器,请访问 Azure 指标资源管理器入门To learn more about Azure Metrics Explorer, visit Getting started with Azure Metrics Explorer.

    Application Insights“服务器指标”图

若要详细了解如何监视 Node.js,请查看其他 AppInsights Node.js 文档To learn more about monitoring Node.js, check out the additional AppInsights Node.js documentation.

清理资源Clean up resources

完成测试后,即可删除资源组和所有相关资源。When you're done testing, you can delete the resource group and all related resources. 为此,请执行以下步骤。To do so follow the steps below.

备注

如果使用了现有资源组,以下说明将不起作用,只需删除单个 Application Insights 资源即可。If you used an existing resource group the instructions below will not work and you will need to just delete the individual Application Insights resource. 请记住,无论何时删除资源组,属于该组的所有底层资源都将被删除。Keep in mind anytime you delete a resource group all underyling resources that are members of that group will be deleted.

  1. 在 Azure 门户的左侧菜单中,选择“资源组” ,然后选择“myResourceGroup” 。From the left-hand menu in the Azure portal, select Resource groups and then select myResourceGroup.
  2. 在资源组页上选择“删除” ,在文本框中输入 myResourceGroup,然后选择“删除” 。On your resource group page, select Delete, enter myResourceGroup in the text box, and then select Delete.

后续步骤Next steps