1 | # Application Insights for Node.js
|
2 |
|
3 | [![npm version](https://badge.fury.io/js/applicationinsights.svg)](http://badge.fury.io/js/applicationinsights)
|
4 | ![Integration Tests CI](https://github.com/microsoft/ApplicationInsights-node.js/workflows/Integration%20Tests%20CI/badge.svg)
|
5 | ![Node.js CI](https://github.com/microsoft/ApplicationInsights-node.js/workflows/Node.js%20CI/badge.svg)
|
6 | ![Back Compatability CI](https://github.com/microsoft/ApplicationInsights-node.js/workflows/Back%20Compatability%20CI/badge.svg)
|
7 |
|
8 | [Azure Application Insights][] monitors your backend services and components after
|
9 | you deploy them to help you [discover and rapidly diagnose performance and other
|
10 | issues][]. Add this SDK to your Node.js services to include deep info about Node.js
|
11 | processes and their external dependencies such as database and cache services.
|
12 | You can use this SDK for your Node.js services hosted anywhere: your datacenter,
|
13 | Azure VMs and Web Apps, and even other public clouds.
|
14 |
|
15 | [Azure Application Insights]: https://azure.microsoft.com/documentation/articles/app-insights-overview/
|
16 | [discover and rapidly diagnose performance and other issues]: https://docs.microsoft.com/azure/application-insights/app-insights-detect-triage-diagnose
|
17 |
|
18 | This library tracks the following out-of-the-box:
|
19 | - Incoming and outgoing HTTP requests
|
20 | - Important system metrics such as CPU usage
|
21 | - Unhandled exceptions
|
22 | - Events from many popular third-party libraries ([see Automatic third-party instrumentation](#automatic-third-party-instrumentation))
|
23 |
|
24 | You can manually track more aspects of your app and system using the API described in the
|
25 | [Track custom telemetry](#track-custom-telemetry) section.
|
26 |
|
27 | ## Supported Node.JS versions
|
28 |
|
29 | | Platform Version | Supported |
|
30 | |------------------|-------------------------------------------------|
|
31 | | Node.JS `v16` | ✅ |
|
32 | | Node.JS `v15` | ✅ |
|
33 | | Node.JS `v14` | ✅ |
|
34 | | Node.JS `v12` | ✅ |
|
35 | | Node.JS `v10` | ✅ |
|
36 | | Node.JS `v8` | ✅ |
|
37 |
|
38 |
|
39 | ## Getting Started
|
40 |
|
41 | > *Important:* On March 31st, 2025, support for instrumentation key ingestion will end. Instrumentation key ingestion will continue to work, but we’ll no longer provide updates or support for the feature. [Transition to connection strings](https://docs.microsoft.com/en-us/azure/azure-monitor/app/migrate-from-instrumentation-keys-to-connection-strings) to take advantage of [new capabilities](https://docs.microsoft.com/en-us/azure/azure-monitor/app/migrate-from-instrumentation-keys-to-connection-strings#new-capabilities).
|
42 |
|
43 | 1. Create an Application Insights resource in Azure by following [these instructions][].
|
44 | 2. Grab the _Connection String_ from the resource you created in
|
45 | step 1. Later, you'll either add it to your app's environment variables or
|
46 | use it directly in your scripts.
|
47 | 3. Add the Application Insights Node.js SDK to your app's dependencies and
|
48 | package.json:
|
49 | ```bash
|
50 | npm install --save applicationinsights
|
51 | ```
|
52 | > *Note:* If you're using TypeScript, please install @types/node package to prevent build issues, this npm package contains built-in typings.
|
53 | 4. As early as possible in your app's code, load the Application Insights
|
54 | package:
|
55 | ```javascript
|
56 | let appInsights = require('applicationinsights');
|
57 | ```
|
58 | 5. Configure the local SDK by calling `appInsights.setup('YOUR_CONNECTION_STRING');`, using
|
59 | the connection string you grabbed in step 2. Or put it in the
|
60 | `APPLICATIONINSIGHTS_CONNECTION_STRING` environment variable and call
|
61 | `appInsights.setup()` without parameters.
|
62 | > For more configuration options see below.
|
63 | 6. Finally, start automatically collecting and sending data by calling
|
64 | `appInsights.start();`.
|
65 |
|
66 | [these instructions]: https://docs.microsoft.com/azure/application-insights/app-insights-nodejs
|
67 |
|
68 |
|
69 | ## Basic Usage
|
70 |
|
71 | > *Important:* `applicationinsights` must be setup *and* started *before* you import anything else. There may be resulting telemetry loss if other libraries are imported first.
|
72 |
|
73 | For out-of-the-box collection of HTTP requests, popular third-party library events,
|
74 | unhandled exceptions, and system metrics:
|
75 |
|
76 | ```javascript
|
77 | let appInsights = require("applicationinsights");
|
78 | appInsights.setup("YOUR_CONNECTION_STRING").start();
|
79 | ```
|
80 |
|
81 | * If the connection string is set in the environment variable
|
82 | APPLICATIONINSIGHTS\_CONNECTION\_STRING, `.setup()` can be called with no
|
83 | arguments. This makes it easy to use different connection strings for different
|
84 | environments.
|
85 |
|
86 | Load the Application Insights library (i.e. `require("applicationinsights")`) as
|
87 | early as possible in your scripts, before loading other packages. This is needed
|
88 | so that the Application Insights library can prepare later packages for tracking.
|
89 | If you encounter conflicts with other libraries doing similar preparation, try
|
90 | loading the Application Insights library after those.
|
91 |
|
92 | Because of the way JavaScript handles callbacks, additional work is necessary to
|
93 | track a request across external dependencies and later callbacks. By default
|
94 | this additional tracking is enabled; disable it by calling
|
95 | `setAutoDependencyCorrelation(false)` as described in the
|
96 | Configuration section below.
|
97 |
|
98 | ## Azure Functions
|
99 |
|
100 | Due to how Azure Functions (and other FaaS services) handle incoming requests, they are not seen as `http` requests to the Node.js runtime. For this reason, Request -> Dependency correlelation will **not** work out of the box.
|
101 | To enable tracking here, you simply need to grab the context from your Function request handler, and wrap your Function with that context.
|
102 |
|
103 | ### Setting up Auto-Correlation for Azure Functions
|
104 |
|
105 | You do not need to make any changes to your existing Function logic.
|
106 | Instead, you can update the `default` export of your `httpTrigger` to be wrapped with some Application Insights logic:
|
107 |
|
108 | ```js
|
109 | ...
|
110 |
|
111 | // Default export wrapped with Application Insights FaaS context propagation
|
112 | export default async function contextPropagatingHttpTrigger(context, req) {
|
113 | // Start an AI Correlation Context using the provided Function context
|
114 | const correlationContext = appInsights.startOperation(context, req);
|
115 |
|
116 | // Wrap the Function runtime with correlationContext
|
117 | return appInsights.wrapWithCorrelationContext(async () => {
|
118 | const startTime = Date.now(); // Start trackRequest timer
|
119 |
|
120 | // Run the Function
|
121 | const result = await httpTrigger(context, req);
|
122 |
|
123 | // Track Request on completion
|
124 | appInsights.defaultClient.trackRequest({
|
125 | name: context.req.method + " " + context.req.url,
|
126 | resultCode: context.res.status,
|
127 | success: true,
|
128 | url: req.url,
|
129 | time: new Date(startTime),
|
130 | duration: Date.now() - startTime,
|
131 | id: correlationContext.operation.parentId,
|
132 | });
|
133 | appInsights.defaultClient.flush();
|
134 |
|
135 | return result;
|
136 | }, correlationContext)();
|
137 | };
|
138 | ```
|
139 |
|
140 | ### Azure Functions Example
|
141 |
|
142 | An example of making an `axios` call to <https://httpbin.org> and returning the reponse.
|
143 |
|
144 | ```js
|
145 | const appInsights = require("applicationinsights");
|
146 | appInsights.setup("<YOUR_CONNECTION_STRING>")
|
147 | .setAutoCollectPerformance(false)
|
148 | .start();
|
149 |
|
150 | const axios = require("axios");
|
151 |
|
152 | /**
|
153 | * No changes required to your existing Function logic
|
154 | */
|
155 | const httpTrigger = async function (context, req) {
|
156 | const response = await axios.get("https://httpbin.org/status/200");
|
157 |
|
158 | context.res = {
|
159 | status: response.status,
|
160 | body: response.statusText,
|
161 | };
|
162 | };
|
163 |
|
164 | // Default export wrapped with Application Insights FaaS context propagation
|
165 | export default async function contextPropagatingHttpTrigger(context, req) {
|
166 | // Start an AI Correlation Context using the provided Function context
|
167 | const correlationContext = appInsights.startOperation(context, req);
|
168 |
|
169 | // Wrap the Function runtime with correlationContext
|
170 | return appInsights.wrapWithCorrelationContext(async () => {
|
171 | const startTime = Date.now(); // Start trackRequest timer
|
172 |
|
173 | // Run the Function
|
174 | const result = await httpTrigger(context, req);
|
175 |
|
176 | // Track Request on completion
|
177 | appInsights.defaultClient.trackRequest({
|
178 | name: context.req.method + " " + context.req.url,
|
179 | resultCode: context.res.status,
|
180 | success: true,
|
181 | url: req.url,
|
182 | time: new Date(startTime),
|
183 | duration: Date.now() - startTime,
|
184 | id: correlationContext.operation.parentId,
|
185 | });
|
186 | appInsights.defaultClient.flush();
|
187 |
|
188 | return result;
|
189 | }, correlationContext)();
|
190 | };
|
191 | ```
|
192 |
|
193 | ## Configuration
|
194 |
|
195 | The appInsights object provides a number of methods to setup SDK behavior. They are
|
196 | listed in the following snippet with their default values.
|
197 |
|
198 | ```javascript
|
199 | let appInsights = require("applicationinsights");
|
200 | appInsights.setup("<YOUR_CONNECTION_STRING>")
|
201 | .setAutoDependencyCorrelation(true)
|
202 | .setAutoCollectRequests(true)
|
203 | .setAutoCollectPerformance(true, true)
|
204 | .setAutoCollectExceptions(true)
|
205 | .setAutoCollectDependencies(true)
|
206 | .setAutoCollectConsole(true, false)
|
207 | .setUseDiskRetryCaching(true)
|
208 | .setAutoCollectPreAggregatedMetrics(true)
|
209 | .setSendLiveMetrics(false)
|
210 | .setAutoCollectHeartbeat(false)
|
211 | .setInternalLogging(false, true)
|
212 | .setDistributedTracingMode(appInsights.DistributedTracingModes.AI_AND_W3C)
|
213 | .enableAutoWebSnippetInjection(false)
|
214 | .start();
|
215 | ```
|
216 |
|
217 | Please review their descriptions in your IDE's built-in type hinting, or [applicationinsights.ts](https://github.com/microsoft/ApplicationInsights-node.js/tree/develop/applicationinsights.ts) for
|
218 | detailed information on what these control, and optional secondary arguments.
|
219 |
|
220 | Note that by default `setAutoCollectConsole` is configured to *exclude* calls to `console.log`
|
221 | (and other `console` methods). By default, only calls to supported third-party loggers
|
222 | (e.g. `winston`, `bunyan`) will be collected. You can change this behavior to *include* calls
|
223 | to `console` methods by using `setAutoCollectConsole(true, true)`.
|
224 |
|
225 | Note that by default `enableAutoWebSnippetInjection` will use the connection string for SDK initialization. If you want to use a different one, you can set it as `enableAutoWebSnippetInjection(true, "your-connection-string")`.
|
226 |
|
227 | The TelemetryClient object contains a `config` property with many optional settings. These can be set as follows:
|
228 | ```
|
229 | client.config.PROPERTYNAME = VALUE;
|
230 | ```
|
231 | These properties are client specific, so you can configure `appInsights.defaultClient`
|
232 | separately from clients created with `new appInsights.TelemetryClient()`.
|
233 |
|
234 | | Property | Description |
|
235 | | ------------------------------- |------------------------------------------------------------------------------------------------------------|
|
236 | | instrumentationKey | Application Insights Instrumentation Key |
|
237 | | endpointUrl | The ingestion endpoint to send telemetry payloads to |
|
238 | | proxyHttpUrl | A proxy server for SDK HTTP traffic (Optional, Default pulled from `http_proxy` environment variable) |
|
239 | | proxyHttpsUrl | A proxy server for SDK HTTPS traffic (Optional, Default pulled from `https_proxy` environment variable) |
|
240 | | maxBatchSize | The maximum number of telemetry items to include in a payload to the ingestion endpoint (Default `250`) |
|
241 | | maxBatchIntervalMs | The maximum amount of time to wait to for a payload to reach maxBatchSize (Default `15000`) |
|
242 | | disableAppInsights | A flag indicating if telemetry transmission is disabled (Default `false`) |
|
243 | | samplingPercentage | The percentage of telemetry items tracked that should be transmitted (Default `100`) |
|
244 | | correlationIdRetryIntervalMs | The time to wait before retrying to retrieve the id for cross-component correlation (Default `30000`) |
|
245 | | correlationHeaderExcludedDomains| A list of domains to exclude from cross-component correlation header injection (Default See [Config.ts][]) |
|
246 | | ignoreLegacyHeaders | Disable including legacy headers in outgoing requests, x-ms-request-id |
|
247 | | distributedTracingMode | Sets the distributed tracing modes (Default=AI) |
|
248 | | enableAutoCollectExternalLoggers| Sets the state of console. If true logger activity will be sent to Application Insights |
|
249 | | enableAutoCollectConsole | Sets the state of logger tracking (enabled by default for third-party loggers only). If true, logger auto collection will include console.log calls (default false) |
|
250 | | enableAutoCollectExceptions | Sets the state of exception tracking (enabled by default). If true uncaught exceptions will be sent to Application Insights |
|
251 | | enableAutoCollectPerformance | Sets the state of performance tracking (enabled by default). If true performance counters will be collected every second and sent to Application Insights |
|
252 | | enableAutoCollectExtendedMetrics| Sets the state of performance tracking (enabled by default). If true, extended metrics counters will be collected every minute and sent to Application Insights |
|
253 | | enableAutoCollectPreAggregatedMetrics | Sets the state of pre aggregated metrics tracking (enabled by default). If true pre aggregated metrics will be collected every minute and sent to Application Insights |
|
254 | | enableAutoCollectHeartbeat | Sets the state of request tracking (enabled by default). If true HeartBeat metric data will be collected every 15 minutes and sent to Application Insights |
|
255 | | enableAutoCollectRequests | Sets the state of request tracking (enabled by default). If true requests will be sent to Application Insights |
|
256 | | enableAutoCollectDependencies | Sets the state of dependency tracking (enabled by default). If true dependencies will be sent to Application Insights |
|
257 | | enableAutoDependencyCorrelation| Sets the state of automatic dependency correlation (enabled by default). If true dependencies will be correlated with requests |
|
258 | | enableUseAsyncHooks | Sets the state of automatic dependency correlation (enabled by default). If true, forces use of experimental async_hooks module to provide correlation. If false, instead uses only patching-based techniques. If left blank, the best option is chosen for you based on your version of Node.js. |
|
259 | | enableUseDiskRetryCaching | If true events that occurred while client is offline will be cached on disk |
|
260 | | enableResendInterval | The wait interval for resending cached events. |
|
261 | | enableMaxBytesOnDisk | The maximum size (in bytes) that the created temporary directory for cache events can grow to, before caching is disabled. |
|
262 | | enableInternalDebugLogging | Enables debug and warning logging for AppInsights itself. If true, enables debug logging |
|
263 | | enableInternalWarningLogging | Enables debug and warning logging for AppInsights itself. If true, enables warning logging |
|
264 | | enableSendLiveMetrics | Enables communication with Application Insights Live Metrics. If true, enables communication with the live metrics service |
|
265 | | disableAllExtendedMetrics | Disable all environment variables set |
|
266 | | extendedMetricDisablers | Disable individual environment variables set. `"extendedMetricDisablers": "..."` |
|
267 | | noDiagnosticChannel | In order to track context across asynchronous calls, some changes are required in third party libraries such as mongodb and redis. By default ApplicationInsights will use diagnostic-channel-publishers to monkey-patch some of these libraries. This property is to disable the feature. Note that by setting this flag, events may no longer be correctly associated with the right operation. |
|
268 | | noPatchModules | Disable individual monkey-patches. Set `noPatchModules` to a comma separated list of packages to disable. e.g. `"noPatchModules": "console,redis"` to avoid patching the console and redis packages. The following modules are available: `azuresdk, bunyan, console, mongodb, mongodb-core, mysql, redis, winston, pg`, and `pg-pool`. Visit the [diagnostic-channel-publishers' README](https://github.com/microsoft/node-diagnostic-channel/blob/master/src/diagnostic-channel-publishers/README.md) for information about exactly which versions of these packages are patched. |
|
269 | | noHttpAgentKeepAlive | HTTPS without a passed in agent |
|
270 | | httpAgent | An http.Agent to use for SDK HTTP traffic (Optional, Default undefined) |
|
271 | | httpsAgent | An https.Agent to use for SDK HTTPS traffic (Optional, Default undefined)
|
272 | | aadTokenCredential| Azure Credential instance to be used to authenticate the App. [AAD Identity Credential Classes](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/identity/identity#credential-classes)
|
273 | | enableAutoWebSnippetInjection(Preview)| Sets the state of automatic web snippet injection (Optional, disabled by default). If true, web snippet will be injected into valid node server http response automatically with the connection string used for SDK initialization
|
274 | | webSnippetConnectionString(Preview)| Sets connection string used for web snippet injection (Optional, Default undefined)| |
|
275 |
|
276 | [Config.ts]: https://github.com/microsoft/ApplicationInsights-node.js/blob/develop/Library/Config.ts
|
277 |
|
278 | All these properties except httpAgent, httpsAgent and aadTokenCredential could be configured using configuration file `applicationinsights.json` located under root folder of applicationinsights package installation folder, Ex: `node_modules/applicationinsights`. These configuration values will be applied to all TelemetryClients created in the SDK.
|
279 |
|
280 |
|
281 | ```javascript
|
282 | {
|
283 | "samplingPercentage": 80,
|
284 | "enableAutoCollectExternalLoggers": true,
|
285 | "enableAutoCollectExceptions": true,
|
286 | "enableAutoCollectHeartbeat": true,
|
287 | "enableSendLiveMetrics": true,
|
288 | ...
|
289 | }
|
290 |
|
291 | ```
|
292 |
|
293 | Custom JSON file could be provided using `APPLICATIONINSIGHTS_CONFIGURATION_FILE` environment variable.
|
294 |
|
295 | ```javascript
|
296 | process.env.APPLICATIONINSIGHTS_CONFIGURATION_FILE = "C:/applicationinsights/config/customConfig.json"
|
297 |
|
298 | // Application Insights SDK setup....
|
299 | ```
|
300 |
|
301 | ### Sampling
|
302 |
|
303 | 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. Set the `samplingPercentage` field on the Config object of a Client to accomplish this. Setting `samplingPercentage` to 100 (the default) means all data will be sent, and 0 means nothing will be sent.
|
304 |
|
305 | If you are using automatic correlation, all data associated with a single request will be included or excluded as a unit.
|
306 |
|
307 | Add code such as the following to enable sampling:
|
308 |
|
309 | ```javascript
|
310 | const appInsights = require("applicationinsights");
|
311 | appInsights.setup("<YOUR_CONNECTION_STRING>");
|
312 | appInsights.defaultClient.config.samplingPercentage = 33; // 33% of all telemetry will be sent to Application Insights
|
313 | appInsights.start();
|
314 | ```
|
315 |
|
316 | ### Multiple roles for multi-component applications
|
317 |
|
318 | 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. (See [Monitor multi-component applications with Application Insights (preview)](https://docs.microsoft.com/azure/application-insights/app-insights-monitor-multi-role-apps))
|
319 |
|
320 | Use the following to set the RoleName field:
|
321 |
|
322 | ```javascript
|
323 | const appInsights = require("applicationinsights");
|
324 | appInsights.setup("<YOUR_CONNECTION_STRING>");
|
325 | appInsights.defaultClient.context.tags[appInsights.defaultClient.context.keys.cloudRole] = "MyRoleName";
|
326 | appInsights.start();
|
327 | ```
|
328 |
|
329 | If running in Azure App service or Azure functions the SDK will automatically populate the cloud role when following code is added:
|
330 | ```javascript
|
331 | const appInsights = require("applicationinsights");
|
332 | appInsights.setup("<YOUR_CONNECTION_STRING>");
|
333 | appInsights.defaultClient.setAutoPopulateAzureProperties(true);
|
334 | appInsights.start();
|
335 | ```
|
336 |
|
337 | ### Automatic web snippet injection[Preview]
|
338 |
|
339 | Automatic web snippet injection is currently in **Preview**. For node server with configuration `enableAutoWebSnippetInjection` set to `true` or environment variable `APPLICATIONINSIGHTS_WEB_SNIPPET_ENABLED = true`, web snippet will be injected into node server response when all of the following requirements are met:
|
340 |
|
341 | - Response has status code `200`.
|
342 | - Response method is `GET`.
|
343 | - Sever response has `Content-Type` html.
|
344 | - Server response must have both `<head>` and `</head>` Tags.
|
345 | - If response is compressed, it must have only one `Content-Encoding` type, and encoding type must be one of `gzip`, `br` or `deflate`.
|
346 | - Response does not contain current /backup snippet CDN endpoints. (current and backup snippet CDN endpoints [here](https://github.com/microsoft/ApplicationInsights-JS#active-public-cdn-endpoints))
|
347 |
|
348 | **Note:** Snippet auto injection may slow down server response time, especially when response size is large or response is compressed. For the case in which some middle layers are applied, it may result in auto injection not working and original response will be returned.
|
349 |
|
350 | ### Automatic third-party instrumentation
|
351 |
|
352 | In order to track context across asynchronous calls, some changes are required in third party libraries such as mongodb and redis.
|
353 | By default ApplicationInsights will use [`diagnostic-channel-publishers`](https://github.com/microsoft/node-diagnostic-channel/tree/master/src/diagnostic-channel-publishers)
|
354 | to monkey-patch some of these libraries.
|
355 | This can be disabled by setting the `APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL` environment variable. Note that by setting that
|
356 | environment variable, events may no longer be correctly associated with the right operation. Individual monkey-patches can be
|
357 | disabled by setting the `APPLICATION_INSIGHTS_NO_PATCH_MODULES` environment variable to a comma separated list of packages to
|
358 | disable, e.g. `APPLICATION_INSIGHTS_NO_PATCH_MODULES=console,redis` to avoid patching the `console` and `redis` packages.
|
359 |
|
360 | The following modules are available: `azuresdk`, `bunyan`, `console`, `mongodb`, `mongodb-core`, `mysql`, `redis`, `winston`,
|
361 | `pg`, and `pg-pool`. Visit the [diagnostic-channel-publishers' README](https://github.com/microsoft/node-diagnostic-channel/blob/master/src/diagnostic-channel-publishers/README.md)
|
362 | for information about exactly which versions of these packages are patched.
|
363 |
|
364 | Automatic instrumentation for several Azure SDKs is also enabled, currently Cognitive Search, Communication Common and Cosmos DB SDKs are not supported.
|
365 | [Javascript Azure SDKs](https://azure.github.io/azure-sdk/releases/latest/index.html#javascript)
|
366 |
|
367 | The `bunyan`, `winston`, and `console` patches will generate Application Insights Trace events based on whether `setAutoCollectConsole` is enabled.
|
368 | The rest will generate Application Insights Dependency events based on whether `setAutoCollectDependencies` is enabled. Make sure that `applicationinsights` is imported **before** any 3rd-party packages for them to be instrumented successfully.
|
369 |
|
370 |
|
371 | ### Live Metrics
|
372 | To enable sending live metrics of your app to Azure, use `setSendLiveMetrics(true)`. Filtering of live metrics in the Portal is currently not supported.
|
373 |
|
374 | ### Extended Metrics
|
375 | >***Note:*** The ability to send extended native metrics was added in version `1.4.0`
|
376 |
|
377 | To enable sending extended native metrics of your app to Azure, simply install the separate native metrics package. The SDK will automatically load it when it is installed and start collecting Node.js native metrics.
|
378 | ```zsh
|
379 | npm install applicationinsights-native-metrics
|
380 | ```
|
381 | Currently, the native metrics package performs autocollection of Garbage Collection CPU time, Event Loop ticks, and heap usage:
|
382 | - **Garbage Collection:** The amount of CPU time spent on each type of garbage collection, and how many occurrences of each type.
|
383 | - **Event Loop:** How many ticks occurred and how much CPU time was spent in total.
|
384 | - **Heap vs Non-Heap:** How much of your app's memory usage is in the heap or non-heap.
|
385 |
|
386 | ### Distributed Tracing Modes
|
387 | By default, this SDK will send headers understood by other applications/services instrumented with an Application Insights SDK. You can optionally enable sending/receiving of [W3C Trace Context](https://github.com/w3c/trace-context) headers in addition to the existing AI headers, so you will not break correlation with any of your existing legacy services. Enabling W3C headers will allow your app to correlate with other services not instrumented with Application Insights, but do adopt this W3C standard.
|
388 |
|
389 | ```js
|
390 | const appInsights = require("applicationinsights");
|
391 | appInsights
|
392 | .setup("<YOUR_CONNECTION_STRING>")
|
393 | .setDistributedTracingMode(appInsights.DistributedTracingModes.AI_AND_W3C)
|
394 | .start()
|
395 | ```
|
396 |
|
397 | ## Track custom telemetry
|
398 |
|
399 | You can track any request, event, metric or exception using the Application
|
400 | Insights client. Examples follow:
|
401 |
|
402 | ```javascript
|
403 | let appInsights = require("applicationinsights");
|
404 | appInsights.setup().start(); // assuming connection string is in environment variables. start() can be omitted to disable any non-custom data
|
405 | let client = appInsights.defaultClient;
|
406 | client.trackEvent({name: "my custom event", properties: {customProperty: "custom property value"}});
|
407 | client.trackException({exception: new Error("handled exceptions can be logged with this method")});
|
408 | client.trackMetric({name: "custom metric", value: 3});
|
409 | client.trackTrace({message: "trace message"});
|
410 | client.trackDependency({target:"http://dbname", name:"select customers proc", data:"SELECT * FROM Customers", duration:231, resultCode:0, success: true, dependencyTypeName: "ZSQL"});
|
411 | client.trackRequest({name:"GET /customers", url:"http://myserver/customers", duration:309, resultCode:200, success:true});
|
412 |
|
413 | let http = require("http");
|
414 | http.createServer( (req, res) => {
|
415 | client.trackNodeHttpRequest({request: req, response: res}); // Place at the beginning of your request handler
|
416 | });
|
417 | ```
|
418 |
|
419 | Note that custom properties are converted to their string representation before being sent, see [Using properties](https://docs.microsoft.com/azure/azure-monitor/app/api-custom-events-metrics#properties) for more information.
|
420 |
|
421 | An example utility using `trackMetric` to measure how long event loop scheduling takes:
|
422 |
|
423 | ```javascript
|
424 | function startMeasuringEventLoop() {
|
425 | var startTime = process.hrtime();
|
426 | var sampleSum = 0;
|
427 | var sampleCount = 0;
|
428 |
|
429 | // Measure event loop scheduling delay
|
430 | setInterval(() => {
|
431 | var elapsed = process.hrtime(startTime);
|
432 | startTime = process.hrtime();
|
433 | sampleSum += elapsed[0] * 1e9 + elapsed[1];
|
434 | sampleCount++;
|
435 | }, 0);
|
436 |
|
437 | // Report custom metric every second
|
438 | setInterval(() => {
|
439 | var samples = sampleSum;
|
440 | var count = sampleCount;
|
441 | sampleSum = 0;
|
442 | sampleCount = 0;
|
443 |
|
444 | if (count > 0) {
|
445 | var avgNs = samples / count;
|
446 | var avgMs = Math.round(avgNs / 1e6);
|
447 | client.trackMetric({name: "Event Loop Delay", value: avgMs});
|
448 | }
|
449 | }, 1000);
|
450 | }
|
451 | ```
|
452 |
|
453 | ## Preprocess data with Telemetry Processors
|
454 |
|
455 | ```javascript
|
456 | public addTelemetryProcessor(telemetryProcessor: (envelope: Contracts.Envelope, context: { http.RequestOptions, http.ClientRequest, http.ClientResponse, Error, correlationContext }) => boolean)
|
457 | ```
|
458 |
|
459 | You can process and filter collected data before it is sent for retention using
|
460 | _Telemetry Processors_. Telemetry processors are called one by one in the
|
461 | order they were added before the telemetry item is sent to the cloud.
|
462 |
|
463 | If a telemetry processor returns false that telemetry item will not be sent.
|
464 |
|
465 | All telemetry processors receive the telemetry data and its envelope to inspect and
|
466 | modify. They also receive a context object. The contents of this object is defined by
|
467 | the `contextObjects` parameter when calling a track method for manually tracked telemetry.
|
468 | For automatically collected telemetry, this object is filled with available request information
|
469 | and the persistent request context as provided by `appInsights.getCorrelationContext()` (if
|
470 | automatic dependency correlation is enabled).
|
471 |
|
472 | The TypeScript type for a telemetry processor is:
|
473 |
|
474 | ```typescript
|
475 | telemetryProcessor: (envelope: ContractsModule.Contracts.Envelope, context: { http.RequestOptions, http.ClientRequest, http.ClientResponse, Error, correlationContext }) => boolean;
|
476 | ```
|
477 |
|
478 | For example, a processor that removes stack trace data from exceptions might be
|
479 | written and added as follows:
|
480 |
|
481 | ```javascript
|
482 | function removeStackTraces ( envelope, context ) {
|
483 | if (envelope.data.baseType === "ExceptionData") {
|
484 | var data = envelope.data.baseData;
|
485 | if (data.exceptions && data.exceptions.length > 0) {
|
486 | for (var i = 0; i < data.exceptions.length; i++) {
|
487 | var exception = data.exceptions[i];
|
488 | exception.parsedStack = null;
|
489 | exception.hasFullStack = false;
|
490 | }
|
491 | }
|
492 | // Add extra properties
|
493 | var originalError = context["Error"];
|
494 | if(originalError && originalError.prop){
|
495 | data.properties = data.properties || {};
|
496 | data.properties.customProperty = originalError.prop;
|
497 | }
|
498 | }
|
499 | return true;
|
500 | }
|
501 |
|
502 | appInsights.defaultClient.addTelemetryProcessor(removeStackTraces);
|
503 | ```
|
504 |
|
505 | More info on the telemetry API is available in [the docs][].
|
506 |
|
507 | [the docs]: https://azure.microsoft.com/documentation/articles/app-insights-api-custom-events-metrics/
|
508 |
|
509 | ## Use multiple Application Insights resources
|
510 |
|
511 | You can create multiple Azure Application Insights resources and send different
|
512 | data to each by using their respective connection string. For
|
513 | example:
|
514 |
|
515 | ```javascript
|
516 | let appInsights = require("applicationinsights");
|
517 |
|
518 | // configure auto-collection under one Connection String
|
519 | appInsights.setup("<YOUR_CONNECTION_STRING>").start();
|
520 |
|
521 | // track some events manually under another connection string
|
522 | let otherClient = new appInsights.TelemetryClient("<YOUR_CONNECTION_STRING>");
|
523 | otherClient.trackEvent({name: "my custom event"});
|
524 | ```
|
525 |
|
526 | ## Examples
|
527 |
|
528 | * Track dependencies
|
529 |
|
530 | ```javascript
|
531 | let appInsights = require("applicationinsights");
|
532 | let client = new appInsights.TelemetryClient();
|
533 |
|
534 | var success = false;
|
535 | let startTime = Date.now();
|
536 | // execute dependency call here....
|
537 | let duration = Date.now() - startTime;
|
538 | success = true;
|
539 |
|
540 | client.trackDependency({target:"http://dbname", name:"select customers proc", data:"SELECT * FROM Customers", duration:duration, resultCode:0, success: true, dependencyTypeName: "ZSQL"});
|
541 | ```
|
542 |
|
543 | * Assign custom properties to be included with all events
|
544 |
|
545 | ```javascript
|
546 | appInsights.defaultClient.commonProperties = {
|
547 | environment: process.env.SOME_ENV_VARIABLE
|
548 | };
|
549 | ```
|
550 |
|
551 | * Manually track all HTTP GET requests
|
552 |
|
553 | Note that all requests are tracked by default. To disable automatic
|
554 | collection, call `.setAutoCollectRequests(false)` before calling `start()`.
|
555 |
|
556 | ```javascript
|
557 | appInsights.defaultClient.trackRequest({name:"GET /customers", url:"http://myserver/customers", duration:309, resultCode:200, success:true});
|
558 | ```
|
559 | Alternatively you can track requests using ```trackNodeHttpRequest``` method:
|
560 |
|
561 | ```javascript
|
562 | var server = http.createServer((req, res) => {
|
563 | if ( req.method === "GET" ) {
|
564 | appInsights.defaultClient.trackNodeHttpRequest({request:req, response:res});
|
565 | }
|
566 | // other work here....
|
567 | res.end();
|
568 | });
|
569 | ```
|
570 |
|
571 | * Track server startup time
|
572 |
|
573 | ```javascript
|
574 | let start = Date.now();
|
575 | server.on("listening", () => {
|
576 | let duration = Date.now() - start;
|
577 | appInsights.defaultClient.trackMetric({name: "server startup time", value: duration});
|
578 | });
|
579 | ```
|
580 |
|
581 | ## Self-diagnostics
|
582 |
|
583 | "Self-diagnostics" refers to internal logging from Application Insights Node.js SDK.
|
584 |
|
585 | This functionality can be helpful for spotting and diagnosing issues with Application Insights itself.
|
586 |
|
587 | By default, Application Insights Node.js SDK logs at warning level to console, following code demonstrate how to enable debug logging as well and generate telemetry for internal logs:
|
588 |
|
589 | ```javascript
|
590 | let appInsights = require("applicationinsights");
|
591 | appInsights.setup("<YOUR_CONNECTION_STRING>")
|
592 | .setInternalLogging(true, true) // Enable both debug and warning logging
|
593 | .setAutoCollectConsole(true, true) // Generate Trace telemetry for winston/bunyan and console logs
|
594 | .start();
|
595 | ```
|
596 |
|
597 | Logs could be put into local file using `APPLICATIONINSIGHTS_LOG_DESTINATION` environment variable, supported values are `file` and `file+console`, a file named `applicationinsights.log` will be generated on tmp folder by default, including all logs, `/tmp` for *nix and `USERDIR/AppData/Local/Temp` for Windows. Log directory could be configured using `APPLICATIONINSIGHTS_LOGDIR` environment variable.
|
598 |
|
599 | ```javascript
|
600 | process.env.APPLICATIONINSIGHTS_LOG_DESTINATION = "file";
|
601 | process.env.APPLICATIONINSIGHTS_LOGDIR = "C:/applicationinsights/logs"
|
602 |
|
603 | // Application Insights SDK setup....
|
604 | ```
|
605 |
|
606 | ## Branches
|
607 |
|
608 | - Ongoing development takes place on the [develop][] branch. **Please submit
|
609 | pull requests to this branch.**
|
610 | - Releases are merged to the [master][] branch and published to [npm][].
|
611 |
|
612 | [master]: https://github.com/microsoft/ApplicationInsights-node.js/tree/master
|
613 | [develop]: https://github.com/microsoft/ApplicationInsights-node.js/tree/develop
|
614 | [npm]: https://www.npmjs.com/package/applicationinsights
|
615 |
|
616 | ## Contributing
|
617 |
|
618 | This project welcomes contributions and suggestions. Most contributions require you to
|
619 | agree to a Contributor License Agreement (CLA) declaring that you have the right to,
|
620 | and actually do, grant us the rights to use your contribution. For details, visit
|
621 | https://cla.microsoft.com.
|
622 |
|
623 | When you submit a pull request, a CLA-bot will automatically determine whether you need
|
624 | to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the
|
625 | instructions provided by the bot. You will only need to do this once across all repositories using our CLA.
|
626 |
|
627 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
|
628 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
|
629 | or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
|
630 |
|
631 | ## Data Collection
|
632 |
|
633 | As this SDK is designed to enable applications to perform data collection which is sent to the Microsoft collection endpoints the following is required to identify our privacy statement.
|
634 |
|
635 | The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft’s privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.
|
636 |
|
637 | ## Trademarks
|
638 |
|
639 | This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft’s Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party’s policies.
|
640 |
|
641 | ## License
|
642 |
|
643 | [MIT](LICENSE) |
\ | No newline at end of file |