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

Application Insights 可以在部署后对后端服务和组件进行监视,以便发现并快速诊断性能问题和其他问题。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, 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 资源Create an Application Insights resource

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

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

  1. 从最新创建的资源中复制资源的检测密钥(也称 ikey)。Copy your resource's instrumentation Key (also called an ikey) from your newly created resource. 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
    

    备注

    如果使用 TypeScript,请勿安装单独的“typings”包。If you are using TypeScript, do not install separate "typings" packages. 此 NPM 包包含内置的 typings。This NPM package contains built-in typings.

  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.

    let appInsights = require('applicationinsights');
    
  4. 也可通过环境变量 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. 手动配置调用 appInsights.setup('[your ikey]');To configure manually call appInsights.setup('[your ikey]');.

    有关其他配置选项,请参阅以下各节。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.

  5. 开始通过调用 appInsights.start(); 自动收集和发送数据。Start automatically collecting and sending data by calling appInsights.start();.

监视应用Monitor your app

SDK 会自动收集有关 Node.js 运行时和一些常见第三方模块的遥测。The SDK automatically gathers telemetry about the Node.js runtime and 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, you can use Application map.

无数据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.

基本用法Basic Usage

对于开箱即用的 HTTP 请求集合、受欢迎的第三方库事件、未经处理的异常和系统指标:For out-of-the-box collection of HTTP requests, popular third-party library events, unhandled exceptions, and system metrics:


let appInsights = require("applicationinsights");
appInsights.setup("[your ikey]").start();

备注

如果在环境变量 APPINSIGHTS_INSTRUMENTATIONKEY 中设置检测密钥,则无需使用参数即可调用 .setup()If the instrumentation key is set in the environment variable APPINSIGHTS_INSTRUMENTATIONKEY, .setup() can be called with no arguments. 这样就可以轻松地针对不同环境使用不同的 ikey。This makes it easy to use different ikeys for different environments.

加载其他包之前,请在脚本中提前加载 Application Insights 库 require("applicationinsights")Load the Application Insights library ,require("applicationinsights"), as early as possible in your scripts before loading other packages. 此操作是必需的,以便 Application Insights 库可以为跟踪准备更高版本的包。This is needed so that the Application Insights library can prepare later packages for tracking. 如果与执行类似准备的其他库发生冲突,请尝试在这些库后面加载 Application Insights 库。If you encounter conflicts with other libraries doing similar preparation, try loading the Application Insights library after those.

由于 JavaScript 处理回调的方式,需要执行额外的工作,以跟踪跨外部依赖项和更高版本回调的请求。Because of the way JavaScript handles callbacks, additional work is necessary to track a request across external dependencies and later callbacks. 默认情况下启用此附加跟踪;可通过调用 setAutoDependencyCorrelation(false) 禁用此跟踪(如以下“配置”部分所述)。By default this additional tracking is enabled; disable it by calling setAutoDependencyCorrelation(false) as described in the configuration section below.

从版本 0.22 之前的版本进行迁移Migrating from versions prior to 0.22

这些是版本 0.22 及更高版本之前的版本之间的重大更改。There are breaking changes between releases prior to version 0.22 and after. 这些更改旨在与其他 Application Insights SDK 保持一致并允许将来进行扩展。These changes are designed to bring consistency with other Application Insights SDKs and allow future extensibility.

通常,可以通过以下方式进行迁移:In general, you can migrate with the following:

  • appInsights.defaultClient 替换对 appInsights.client 的引用。Replace references to appInsights.client with appInsights.defaultClient.
  • new appInsights.TelemetryClient() 替换对 appInsights.getClient() 的引用Replace references to appInsights.getClient() with new appInsights.TelemetryClient()
  • 将所有参数替换为 client.track* 方法,其中有一个包含命名属性的对象用作参数。Replace all arguments to client.track* methods with a single object containing named properties as arguments. 有关每种类型的遥测的例外对象,请参阅 IDE 的内置类型提示或 TelemetryTypesSee your IDE's built-in type hinting or TelemetryTypes for the excepted object for each type of telemetry.

如果在不将 SDK 配置函数链接到 appInsights.setup() 的情况下访问这些函数,现在可以在 appInsights.Configurations(例如 appInsights.Configuration.setAutoCollectDependencies(true))中找到这些函数。If you access SDK configuration functions without chaining them to appInsights.setup(), you can now find these functions at appInsights.Configurations (for example, appInsights.Configuration.setAutoCollectDependencies(true)). 查看下一节中对默认配置所做的更改。Review the changes to the default configuration in the next section.

SDK 配置SDK configuration

appInsights 对象提供了许多配置方法。The appInsights object provides a number of configuration methods. 以下代码片段中列出了这些方法及其默认值。They are listed in the following snippet with their default values.

let appInsights = require("applicationinsights");
appInsights.setup("<instrumentation_key>")
    .setAutoDependencyCorrelation(true)
    .setAutoCollectRequests(true)
    .setAutoCollectPerformance(true, true)
    .setAutoCollectExceptions(true)
    .setAutoCollectDependencies(true)
    .setAutoCollectConsole(true)
    .setUseDiskRetryCaching(true)
    .setSendLiveMetrics(false)
    .setDistributedTracingMode(appInsights.DistributedTracingModes.AI)
    .start();

若要让服务中的事件完全相关联,请确保设置 .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.

有关这些控件和可选辅助参数的详细信息,请在 IDE 的内置类型提示或 applicationinsights.config 中查看其说明。Review their descriptions in your IDE's built-in type hinting, or applicationinsights.ts for detailed information on what these control, and optional secondary arguments.

备注

默认情况下,setAutoCollectConsole 配置为排除对 console.log(以及其他控制台方法)的调用。By default setAutoCollectConsole is configured to exclude calls to console.log (and other console methods). 将只收集对受支持的第三方记录器(例如 winston 和 bunyan)的调用。Only calls to supported third-party loggers (for example, winston and bunyan) will be collected. 你可以通过使用 setAutoCollectConsole(true, true) 将此行为更改为包括对 console 方法的调用。You can change this behavior to include calls to console methods by using setAutoCollectConsole(true, true).

采样Sampling

默认情况下,SDK 会将收集的所有数据发送到 Application Insights 服务。By default, the SDK will send all collected data to the Application Insights service. 如果收集了大量数据,则可能需要启用采样来减少发送的数据量。If you collect a lot of data, you might want to enable sampling to reduce the amount of data sent. 要完成此操作,请设置客户端的 config 对象上的 samplingPercentage 字段。Set the samplingPercentage field on the config object of a client to accomplish this. samplingPercentage 设置为100(默认值)表示将发送所有数据,设置为 0 则表示不会发送任何内容。Setting samplingPercentage to 100(the default) means all data will be sent and 0 means nothing will be sent.

如果使用自动关联,则会将与单个请求关联的所有数据作为一个单元包括或排除。If you are using automatic correlation, all data associated with a single request will be included or excluded as a unit.

若要启用采样,请添加以下代码:Add code such as the following to enable sampling:

const appInsights = require("applicationinsights");
appInsights.setup("<instrumentation_key>");
appInsights.defaultClient.config.samplingPercentage = 33; // 33% of all telemetry will be sent to Application Insights
appInsights.start();

多组件应用程序的多个角色Multiple roles for multi-components applications

如果你的应用程序包含多个你希望使用相同检测密钥来检测的组件,并且仍在门户中将这些组件视为单独的单元,就像它们使用单独的检测密钥一样(例如,就像应用程序映射上的单独节点一样),你可能需要手动配置“用户类型”字段,以将一个组件的遥测与用于将数据发送到 Application Insights 资源的其他组件区分开来。If your application consists of multiple components that you wish to instrument all with the same instrumentation key and still see these components as separate units in the portal, as if they were using separate instrumentation keys (for example, as separate nodes on the Application Map), you may need to manually configure the RoleName field to distinguish one component's telemetry from other components sending data to your Application Insights resource.

使用以下内容设置 RoleName 字段:Use the following to set the RoleName field:

const appInsights = require("applicationinsights");
appInsights.setup("<instrumentation_key>");
appInsights.defaultClient.context.tags[appInsights.defaultClient.context.keys.cloudRole] = "MyRoleName";
appInsights.start();

自动第三方检测Automatic third-party instrumentation

为了跨异步调用跟踪上下文,某些第三方库(如 MongoDB 和 Redis)需要进行一些更改。In order to track context across asynchronous calls, some changes are required in third party libraries such as MongoDB and Redis. 默认情况下,Application Insights 将使用 diagnostic-channel-publishers 猴子补丁来修补一些库。By default, Application Insights will use diagnostic-channel-publishers to monkey-patch some of these libraries. 可通过设置 APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL 环境变量禁用此操作。This can be disabled by setting the APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL environment variable.

备注

通过设置该环境变量,事件可能不再与正确的操作正确关联。By setting that environment variable, events may no longer be correctly associated with the right operation.

可以通过将 APPLICATION_INSIGHTS_NO_PATCH_MODULES 环境变量设置为要禁用的包的逗号分隔列表(例如 APPLICATION_INSIGHTS_NO_PATCH_MODULES=console,redis)来禁用单个猴子补丁,以避免修补 consoleredis 包。Individual monkey-patches can be disabled by setting the APPLICATION_INSIGHTS_NO_PATCH_MODULES environment variable to a comma separated list of packages to disable (for example, APPLICATION_INSIGHTS_NO_PATCH_MODULES=console,redis) to avoid patching the console and redis packages.

目前已检测到 9 个包:bunyanconsolemongodbmongodb-coremysqlrediswinstonpgpg-poolCurrently there are nine packages that are instrumented: bunyan,console,mongodb,mongodb-core,mysql,redis,winston,pg, and pg-pool. 如需深入了解要修补这些包的哪个版本,请访问 diagnostic-channel-publishers 自述文件Visit the diagnostic-channel-publishers' README for information about exactly which version of these packages are patched.

bunyanwinstonconsole 补丁将根据是否启用 setAutoCollectConsole 生成 Application Insights 跟踪事件。The bunyan, winston, and console patches will generate Application Insights trace events based on whether setAutoCollectConsole is enabled. 其余补丁将根据是否启用 setAutoCollectDependencies 生成 Insights Dependency 事件。The rest will generate Application Insights Dependency events based on whether setAutoCollectDependencies is enabled.

实时指标Live Metrics

若要允许将实时指标从应用发送到 Azure,请使用 setSendLiveMetrics(true)To enable sending Live Metrics from your app to Azure, use setSendLiveMetrics(true). 目前不支持在门户中筛选实时指标。Filtering of live metrics in the portal is currently not supported.

扩展指标Extended metrics

备注

1.4.0 版本中添加了发送扩展本机指标的功能。The ability to send extended native metrics was added in version 1.4.0

若要允许将扩展本机指标从应用发送到 Azure,请安装单独的本机指标包。To enable sending extended native metrics from your app to Azure, install the separate native metrics package. SDK 将在安装后自动加载并开始收集 node.js 本机指标。The SDK will automatically load when it is installed and start collecting Node.js native metrics.

npm install applicationinsights-native-metrics

目前,本机指标包会自动收集垃圾回收 CPU 时间、事件循环计时和堆使用情况:Currently, the native metrics package performs autocollection of garbage collection CPU time, event loop ticks, and heap usage:

  • 垃圾回收:每种类型的垃圾回收所用的 CPU 时间,以及每种类型出现的次数。Garbage collection: The amount of CPU time spent on each type of garbage collection, and how many occurrences of each type.
  • 事件循环:发生了多少个计时周期,以及总共花费了多少 CPU 时间。Event loop: How many ticks occurred and how much CPU time was spent in total.
  • 堆与非堆:应用的内存使用情况有多少位于堆或非堆中。Heap vs non-heap: How much of your app's memory usage is in the heap or non-heap.

分布式跟踪模式Distributed Tracing modes

默认情况下,SDK 将发送被其他应用程序/服务理解的标头,可通过 Application Insights SDK 检测到此类应用程序/服务。By default, the SDK will send headers understood by other applications/services instrumented with an Application Insights SDK. 除了现有的 AI 标头,还可以根据需要启用 W3C 跟踪上下文标头的发送/接收,这样就不会中断与任何现有旧服务的关联。You can optionally enable sending/receiving of W3C Trace Context headers in addition to the existing AI headers, so you will not break correlation with any of your existing legacy services. 启用 W3C 标头将允许你的应用与未通过 Application Insights 检测的其他服务相关联,但会采用这一 W3C 标准。Enabling W3C headers will allow your app to correlate with other services not instrumented with Application Insights, but do adopt this W3C standard.

const appInsights = require("applicationinsights");
appInsights
  .setup("<your ikey>")
  .setDistributedTracingMode(appInsights.DistributedTracingModes.AI_AND_W3C)
  .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 in env var. start() can be omitted to disable any non-custom data
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 = new appInsights.TelemetryClient();

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

client.trackDependency({target:"http://dbname", name:"select customers proc", data:"SELECT * FROM Customers", duration:duration, resultCode:0, success: true, dependencyTypeName: "ZSQL"});;

使用 trackMetric 度量事件循环计划所花费的时间的示例实用工具:An example utility using trackMetric to measure how long event loop scheduling takes:

function startMeasuringEventLoop() {
  var startTime = process.hrtime();
  var sampleSum = 0;
  var sampleCount = 0;

  // Measure event loop scheduling delay
  setInterval(() => {
    var elapsed = process.hrtime(startTime);
    startTime = process.hrtime();
    sampleSum += elapsed[0] * 1e9 + elapsed[1];
    sampleCount++;
  }, 0);

  // Report custom metric every second
  setInterval(() => {
    var samples = sampleSum;
    var count = sampleCount;
    sampleSum = 0;
    sampleCount = 0;

    if (count > 0) {
      var avgNs = samples / count;
      var avgMs = Math.round(avgNs / 1e6);
      client.trackMetric({name: "Event Loop Delay", value: avgMs});
    }
  }, 1000);
}

将自定义属性添加到所有事件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 manually track HTTP GET requests:

备注

默认情况下跟踪所有请求。All requests are tracked by default. 若要禁用自动收集,请在调用 start() 之前调用 .setAutoCollectRequests(false)。To disable automatic collection, call .setAutoCollectRequests(false) before calling start().

appInsights.defaultClient.trackRequest({name:"GET /customers", url:"http://myserver/customers", duration:309, resultCode:200, success:true});

也可使用 trackNodeHttpRequest 方法跟踪请求:Alternatively you can track requests using trackNodeHttpRequest method:

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});
});

使用遥测处理器预处理数据Preprocess data with telemetry processors

在发送数据之前,可以使用遥测处理器来处理和筛选收集的数据以进行保留。You can process and filter collected data before it is sent for retention using Telemetry Processors. 遥测处理器在遥测项发送到云之前按其添加顺序依次调用。Telemetry processors are called one by one in the order they were added before the telemetry item is sent to the cloud.

public addTelemetryProcessor(telemetryProcessor: (envelope: Contracts.Envelope, context: { http.RequestOptions, http.ClientRequest, http.ClientResponse, correlationContext }) => boolean)

如果遥测处理器返回 false,则不会发送该遥测项。If a telemetry processor returns false, that telemetry item will not be sent.

所有遥测处理器都接收遥测数据及其信封来检查和修改。All telemetry processors receive the telemetry data and its envelope to inspect and modify. 它们还会接收上下文对象。They also receive a context object. 在为手动跟踪的遥测调用跟踪方法时,此对象的内容由 contextObjects 参数定义。The contents of this object is defined by the contextObjects parameter when calling a track method for manually tracked telemetry. 对于自动收集的遥测,此对象使用 appInsights.getCorrelationContext() 提供的可用请求信息和持久性请求内容(如果启用了自动相关性关联)进行填充。For automatically collected telemetry, this object is filled with available request information and the persistent request content as provided by appInsights.getCorrelationContext() (if automatic dependency correlation is enabled).

遥测处理器的 TypeScript 类型为:The TypeScript type for a telemetry processor is:

telemetryProcessor: (envelope: ContractsModule.Contracts.Envelope, context: { http.RequestOptions, http.ClientRequest, http.ClientResponse, correlationContext }) => boolean;

例如,可以按如下所示编写并添加从异常中删除堆栈跟踪数据的处理器:For example, a processor that removes stacks trace data from exceptions might be written and added as follows:

function removeStackTraces ( envelope, context ) {
  if (envelope.data.baseType === "Microsoft.ApplicationInsights.ExceptionData") {
    var data = envelope.data.baseData;
    if (data.exceptions && data.exceptions.length > 0) {
      for (var i = 0; i < data.exceptions.length; i++) {
        var exception = data.exceptions[i];
        exception.parsedStack = null;
        exception.hasFullStack = false;
      }
    }
  }
  return true;
}

appInsights.defaultClient.addTelemetryProcessor(removeStackTraces);

使用多个检测密钥Use multiple instrumentation keys

可以创建多个 Application Insights 资源,并使用各自的检测密钥 (ikey) 将不同数据发送到每个资源。You can create multiple Application Insights resources and send different data to each by using their respective instrumentation keys ("ikey").

例如:For example:

let appInsights = require("applicationinsights");

// configure auto-collection under one ikey
appInsights.setup("_ikey-A_").start();

// track some events manually under another ikey
let otherClient = new appInsights.TelemetryClient("_ikey-B_");
otherClient.trackEvent({name: "my custom event"});

高级配置选项Advanced configuration options

客户端对象包含一个 config 属性,该属性具有多个适用于高级方案的可选设置。The client object contains a config property with many optional settings for advanced scenarios. 可按如下所示设置这些设置:These can be set as follows:

client.config.PROPERTYNAME = VALUE;

这些属性是特定于客户端的,因此你可以从使用 new appInsights.TelemetryClient() 创建的客户端单独配置 appInsights.defaultClientThese properties are client specific, so you can configure appInsights.defaultClient separately from clients created with new appInsights.TelemetryClient().

PropertyProperty 说明Description
instrumentationKeyinstrumentationKey Application Insights 资源的标识符。An identifier for your Application Insights resource.
endpointUrlendpointUrl 接收遥测有效负载的引入终结点。The ingestion endpoint to send telemetry payloads to.
quickPulseHostquickPulseHost 接收实时指标遥测的实时指标流主机。The Live Metrics Stream host to send live metrics telemetry to.
proxyHttpUrlproxyHttpUrl SDK HTTP 流量的代理服务器(可选,默认拉取自 http_proxy 环境变量)。A proxy server for SDK HTTP traffic (Optional, Default pulled from http_proxy environment variable).
proxyHttpsUrlproxyHttpsUrl SDK HTTPS 流量的代理服务器(可选,默认拉取自 https_proxy 环境变量)。A proxy server for SDK HTTPS traffic (Optional, Default pulled from https_proxy environment variable).
httpAgenthttpAgent 用于 SDK HTTP 流量的 http.Agent(可选,默认为未定义)。An http.Agent to use for SDK HTTP traffic (Optional, Default undefined).
httpsAgenthttpsAgent 用于 SDK HTTPS 流量的 http.Agent(可选,默认为未定义)。An https.Agent to use for SDK HTTPS traffic (Optional, Default undefined).
maxBatchSizemaxBatchSize 要包括在引入终结点的有效负载中的最大遥测项数(默认为 250)。The maximum number of telemetry items to include in a payload to the ingestion endpoint (Default 250).
maxBatchIntervalMsmaxBatchIntervalMs 有效负载达到 maxBatchSize 之前要等待的最长时间(默认为 15000)。The maximum amount of time to wait to for a payload to reach maxBatchSize (Default 15000).
disableAppInsightsdisableAppInsights 一个标志,用于指示是否禁用遥测传输(默认为 false)。A flag indicating if telemetry transmission is disabled (Default false).
samplingPercentagesamplingPercentage 应传输的已跟踪遥测项的百分比(默认为 100)。The percentage of telemetry items tracked that should be transmitted (Default 100).
correlationIdRetryIntervalMscorrelationIdRetryIntervalMs 重试检索交叉组件相关的 ID 之前要等待的时间(默认为 30000)。The time to wait before retrying to retrieve the ID for cross-component correlation (Default 30000).
correlationHeaderExcludedDomainscorrelationHeaderExcludedDomains 要从交叉组件相关标头注入中排除的域列表(默认值,请参阅 Config.ts)。A list of domains to exclude from cross-component correlation header injection (Default See Config.ts).

后续步骤Next steps