Application Insights SDK for Node.js part 2 : Track events
Tags: applicationinsights, azure, node
Published: 2020-01-14 08:04:59

---
title: Application Insights SDK for Node.js part 2 : Track events
published: true
description: Take a deeper look into Application Insight SDK for Node.js
tags: applicationinsights,azure,nodejs
cover_image: https://azurecomcdn.azureedge.net/cvt-143af90d7db8d8220163967e056e9185e6a4b2273729389738a071b204137b5b/images/page/services/monitor/application-monitoring.png
---

In the [previous](https://dev.to/kenakamu/application-insights-sdk-for-node-js-3ki1) article, I explain how Application Insights SDK for Node.js sends telemetry data to servers. In this article, I demonstrate it.

# Sample application

It's super straight forward sample. Just create new node.js app and use following code as index.js

```javascript
var appInsights = require('applicationinsights');
appInsights.setup('<instrumentation_key>').start();
var client = appInsights.defaultClient;
appInsights.defaultClient.addTelemetryProcessor(envelope => {
    envelope.tags["ai.cloud.role"] = "myapp";
    envelope.tags["ai.cloud.roleInstance"] = "myapp1"
});

var express = require('express');
var app = express();

app.get('/', (req, res) => {

    let customMetric = Math.random() * 50 + 50;
    client.trackEvent({ name: "my custom event", properties: { customProperty: "my custom event" } });
    client.trackMetric({ name: "custom metric", value: customMetric}); // generate metric [50, 100]

    res.send(customMetric.toString());
});

app.listen(8888);

process.on('SIGINT', (code) => {
    setTimeout(() => {
        client.flush({ isAppCrashing: true });
        console.log("flushed");
        process.exit();
    }, 0);
});
```

Once you start the application, access to http://localhost:8888 and you will see the result.

![](https://thepracticaldev.s3.amazonaws.com/i/dpan1fkksx4ok5qso1l7.jpg)

# Normal behavior

When everything goes fine, both event log and metric are sent and stored in the Application Insights Server. As you see in the screenshot below, you can filter results by **| where cloud_RoleName  contains "myapp"**

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/dusgriquw5qm0kcteht9.jpg)

# When terminate the application by Ctrl+C

As explained in the [previous article](https://dev.to/kenakamu/application-insights-sdk-for-node-js-3ki1), the SDK doesn't send each event immediately. This infers there is some chance to loose the data if the Node.js application is exit and if you don't flush the data.

I use **process.on** to test the behavior.

1\. Start the application in console.

2\. Go to http://localhost:8888 and generate some events.

3\. Terminate the application by Ctrl+C.

4\. You see cache is written to disk. The path is path.join(os.tmpdir(), Sender.TEMPDIR_PREFIX + this._config.instrumentationKey)

![](https://thepracticaldev.s3.amazonaws.com/i/8ce02j2p4ju320dxb971.jpg)

5\. Now restart the Node.js application to see the data is saved to cloud later. It may take a bit of time depending on how many data you cached.

![](https://thepracticaldev.s3.amazonaws.com/i/9yr4t66ft5ddb3xina4u.jpg)

# When network is down

Even though my wifi is off, I still can access to my server locally, which generates telemetry.

In this case, the behavior is similar to previous scenario, which cache the data to disk.

# Re-write the data

While SDK cannot access to the internet, I have an opportunity to manually tweak the file. This time, I just modified the data from "my custom event" to "my custom event offline" for fun. After reconnecting to the internet, the data is stored as expected. *Don't mind the timestamp as I tested this earlier than previous scenario :)

![](https://thepracticaldev.s3.amazonaws.com/i/tfc469updrcnifp2w53v.jpg)

# Summary

The SDK behave exactly as I expected. Still there are several things to keep in mind.

- Handle some event explicitly (Exception will be handled by default)
- There is a minute interval for each file to be uploaded by default, so it may take a bit of time.

I talk about application map next.

[Go to next article](https://dev.to/kenakamu/application-insights-sdk-for-node-js-part-3-application-map-228h)