使用 Application Insights 监视 Node.js 服务和应用Monitor your Node.js services and apps with Application Insights

Azure Application Insights 可以在部署后对后端服务和组件进行监视,以便发现并快速诊断性能问题和其他问题。Azure Application Insights monitors your backend services and components after deployment, to help you discover and rapidly diagnose performance and other issues. 可以将 Application Insights 用于 Node.js 服务,不管这些服务是托管在数据中心、Azure VM 和 Web 应用中,还是在其他公有云中。You can use Application Insights for Node.js services that are hosted in your datacenter, in Azure VMs and web apps, and even in other public clouds.

若要接收、存储和探索监视数据,请将 SDK 包括到代码中,然后在 Azure 中设置相应的 Application Insights 资源。To receive, store, and explore your monitoring data, include the SDK in your code, and then set up a corresponding Application Insights resource in Azure. SDK 会将数据发送到该资源进行进一步的分析和探索。The SDK sends data to that resource for further analysis and exploration.

Node.js SDK 可以自动监视传入和传出的 HTTP 请求、异常和某些系统指标。The Node.js SDK can automatically monitor incoming and outgoing HTTP requests, exceptions, and some system metrics. 从 0.20 版开始,SDK 也可监视某些常用的第三方程序包,例如 MongoDB、MySQL、Redis。Beginning in version 0.20, the SDK also can monitor some common third-party packages, like MongoDB, MySQL, and Redis. 所有与传入 HTTP 请求相关的事件都会进行关联,以加快故障排除速度。All events related to an incoming HTTP request are correlated for faster troubleshooting.

可以使用 TelemetryClient API 手动检测和监视应用和系统的其他方面。You can use the TelemetryClient API to manually instrument and monitor additional aspects of your app and system. 本文后面会更详细地介绍 TelemetryClient API。We describe the TelemetryClient API in more detail later in this article.

入门Get started

请完成以下任务,为应用或服务设置监视。Complete the following tasks to set up monitoring for an app or service.

先决条件Prerequisites

开始之前,请确保拥有 Azure 订阅,否则请获取一个新的试用版Before you begin, make sure that you have an Azure subscription, or get a new one for trial. 如果组织已经拥有 Azure 订阅,管理员可以按照这些说明你将添加到该订阅。If your organization already has an Azure subscription, an administrator can follow these instructions to add you to it.

设置 Application Insights 资源Set up an Application Insights resource

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

  2. 选择“创建资源” > “开发人员工具” > “Application Insights”。Select Create a resource > Developer tools > Application Insights. 该资源包括用于接收遥测数据的终结点、用于该数据的存储、保存的报告和仪表板、规则和警报配置等。The resource includes an endpoint for receiving telemetry data, storage for this data, saved reports and dashboards, rule and alert configuration, and more.

  3. 在资源创建页的“应用程序类型”框中选择“Node.js 应用程序”。 On the resource creation page, in the Application Type box, select Node.js Application. 应用类型决定了创建的默认仪表板和报告。The app type determines the default dashboards and reports that are created. (任何 Application Insights 资源都可以收集任何语言和平台的数据。)(Any Application Insights resource can collect data from any language and platform.)

设置 Node.js SDKSet up the Node.js SDK

将 SDK 包括到应用中,使之能够收集数据。Include the SDK in your app, so it can gather data.

  1. 从 Azure 门户中复制资源的检测密钥(也称 ikey)。 Copy your resource's Instrumentation Key (also called an ikey) from the Azure portal. Application Insights 使用 ikey 将数据映射到 Azure 资源。Application Insights uses the ikey to map data to your Azure resource. 必须在环境变量或代码中指定 ikey,然后 SDK 才能使用该 ikey。Before the SDK can use your ikey, you must specify the ikey in an environment variable or in your code.

    复制检测密钥

  2. 通过 package.json 将 Node.js SDK 库添加到应用的依赖项。Add the Node.js SDK library to your app's dependencies via package.json. 从应用的根文件夹,运行:From the root folder of your app, run:

    npm install applicationinsights --save
    
  3. 将该库显式加载到代码中。Explicitly load the library in your code. 由于 SDK 将检测注入到许多其他库中,请尽早加载该库,甚至应赶在其他 require 语句之前加载。Because the SDK injects instrumentation into many other libraries, load the library as early as possible, even before other require statements.

    在第一个 .js 文件顶部添加以下代码。At the top of your first .js file, add the following code. setup 方法配置默认情况下用于所有已跟踪项的密钥(因此也配置 Azure 资源)。The setup method configures the ikey (and thus, the Azure resource) to be used by default for all tracked items.

    const appInsights = require("applicationinsights");
    appInsights.setup("<instrumentation_key>");
    appInsights.start();
    

    也可通过环境变量 APPINSIGHTS_INSTRUMENTATIONKEY 来提供 ikey,不必手动将其传递给 setup()new appInsights.TelemetryClient()You also can provide an ikey via the environment variable APPINSIGHTS_INSTRUMENTATIONKEY, instead of passing it manually to setup() or new appInsights.TelemetryClient(). 这种做法允许将 ikey 脱离已提交的源代码,因此可以为不同的环境指定不同的 ikey。This practice lets you keep ikeys out of committed source code, and you can specify different ikeys for different environments.

    有关其他配置选项,请参阅以下各节。For additional configuration options, see the following sections.

    可以设置 appInsights.defaultClient.config.disableAppInsights = true,尝试在不发送遥测的情况下使用 SDK。You can try the SDK without sending telemetry by setting appInsights.defaultClient.config.disableAppInsights = true.

监视应用Monitor your app

SDK 自动收集 Node.js 运行时和一些常用第三方模块的遥测。The SDK automatically gathers telemetry about the Node.js runtime and about some common third-party modules. 请使用应用程序生成部分此类数据。Use your application to generate some of this data.

然后,在 Azure 门户中转到此前创建的 Application Insights 资源。Then, in the Azure portal go to the Application Insights resource that you created earlier. 在“概览时间线” 中,查找前面的几个数据点。In the Overview timeline, look for your first few data points. 若要查看更多详细数据,请在图表中选择不同的组件。To see more detailed data, select different components in the charts.

若要查看应用的已发现拓扑,请选择“应用程序映射”按钮。 To view the topology that is discovered for your app, select the Application map button. 在映射中选择组件,以便查看更多详细信息。Select components in the map to see more details.

简单的应用映射

若要详细了解应用并排查问题,请在“调查”部分选择可用的其他视图。 To learn more about your app, and to troubleshoot problems, in the INVESTIGATE section, select the other views that are available.

“调查”部分

没有数据?No data?

由于 SDK 对要提交的数据进行批处理,项目在门户中显示之前可能会有一段延迟。Because the SDK batches data for submission, there might be a delay before items are displayed in the portal. 如果在资源中看不到数据,可尝试下面的部分修复手段:If you don't see data in your resource, try some of the following fixes:

  • 继续使用应用程序。Continue to use the application. 通过更多操作生成更多遥测。Take more actions to generate more telemetry.
  • 在门户资源视图中单击“刷新”。 Click Refresh in the portal resource view. 图表会定期自行刷新,但手动刷新会强制图表立刻刷新。Charts periodically refresh on their own, but manually refreshing forces them to refresh immediately.
  • 验证所需传出端口是否已打开。Verify that required outgoing ports are open.
  • 使用搜索查找特定事件。Use Search to look for specific events.
  • 查看常见问题解答Check the FAQ.

SDK 配置SDK configuration

SDK 的配置方法和默认值在以下代码示例中列出。The SDK's configuration methods and default values are listed in the following code example.

若要让服务中的事件完全相关联,请确保设置 .setAutoDependencyCorrelation(true)To fully correlate events in a service, be sure to set .setAutoDependencyCorrelation(true). 设置此选项以后,SDK 即可在 Node.js 中跨异步回调跟踪上下文。With this option set, the SDK can track context across asynchronous callbacks in Node.js.

const appInsights = require("applicationinsights");
appInsights.setup("<instrumentation_key>")
    .setAutoDependencyCorrelation(true)
    .setAutoCollectRequests(true)
    .setAutoCollectPerformance(true)
    .setAutoCollectExceptions(true)
    .setAutoCollectDependencies(true)
    .setAutoCollectConsole(true)
    .setUseDiskRetryCaching(true)
    .start();

TelemetryClient APITelemetryClient API

有关 TelemetryClient API 的完整说明,请参阅用于处理自定义事件和指标的 Application Insights APIFor a full description of the TelemetryClient API, see Application Insights API for custom events and metrics.

可以使用 Application Insights Node.js SDK 跟踪任何请求、事件、指标或异常。You can track any request, event, metric, or exception by using the Application Insights Node.js SDK. 以下代码示例演示了部分可用 API:The following code example demonstrates some of the APIs that you can use:

let appInsights = require("applicationinsights");
appInsights.setup().start(); // assuming ikey is in env var
let client = appInsights.defaultClient;

client.trackEvent({name: "my custom event", properties: {customProperty: "custom property value"}});
client.trackException({exception: new Error("handled exceptions can be logged with this method")});
client.trackMetric({name: "custom metric", value: 3});
client.trackTrace({message: "trace message"});
client.trackDependency({target:"http://dbname", name:"select customers proc", data:"SELECT * FROM Customers", duration:231, resultCode:0, success: true, dependencyTypeName: "ZSQL"});
client.trackRequest({name:"GET /customers", url:"http://myserver/customers", duration:309, resultCode:200, success:true});

let http = require("http");
http.createServer( (req, res) => {
  client.trackNodeHttpRequest({request: req, response: res}); // Place at the beginning of your request handler
});

跟踪依赖项Track your dependencies

使用以下代码跟踪依赖项:Use the following code to track your dependencies:

let appInsights = require("applicationinsights");
let client = appInsights.defaultClient;

var success = false;
let startTime = Date.now();
// Execute dependency call here...
let duration = Date.now() - startTime;
success = true;

client.trackDependency({dependencyTypeName: "dependency name", name: "command name", duration: duration, success: success});

将自定义属性添加到所有事件Add a custom property to all events

使用以下代码向所有事件添加自定义属性:Use the following code to add a custom property to all events:

appInsights.defaultClient.commonProperties = {
    environment: process.env.SOME_ENV_VARIABLE
};

跟踪 HTTP GET 请求Track HTTP GET requests

使用以下代码跟踪 HTTP GET 请求:Use the following code to track HTTP GET requests:

var server = http.createServer((req, res) => {
    if ( req.method === "GET" ) {
            appInsights.defaultClient.trackNodeHttpRequest({request: req, response: res});
    }
    // Other work here...
    res.end();
});

跟踪服务器启动时间Track server startup time

使用以下代码跟踪服务器启动时间:Use the following code to track server startup time:

let start = Date.now();
server.on("listening", () => {
    let duration = Date.now() - start;
    appInsights.defaultClient.trackMetric({name: "server startup time", value: duration});
});

后续步骤Next steps