Application Insights SDK for Node.js part 4 : Out of box telemetries - Basics and Console
Tags: applicationinsights, azure, node
Published: 2020-01-26 09:48:18

---
title: Application Insights SDK for Node.js part 4 : Out of box telemetries - Basics and Console
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-part-3-application-map-228h) article, I looked into Application Map which illustrate my entire application components. In this article, I go back to Node.js SDK and look into out of box telemetries.

# setup/start function

At the beginning of the application, I initialize the application insight client instance and call **setup** and **start** function.

```javascript
var appInsights = require("applicationinsights");
appInsights.setup("<instrumentation_key>").start();
```
When I look at [GitHub: ApplicationInsights.ts](https://github.com/microsoft/ApplicationInsights-node.js/blob/develop/applicationinsights.ts), it setup out of box telemetries and starts colleting them.

```javascript
export function setup(instrumentationKey?: string) {
    if(!defaultClient) {
        defaultClient = new TelemetryClient(instrumentationKey);
        _console = new AutoCollectConsole(defaultClient);
        _exceptions = new AutoCollectExceptions(defaultClient);
        _performance = new AutoCollectPerformance(defaultClient);
        _serverRequests = new AutoCollectHttpRequests(defaultClient);
        _clientRequests = new AutoCollectHttpDependencies(defaultClient);
        if (!_nativePerformance) {
            _nativePerformance = new AutoCollectNativePerformance(defaultClient);
        }
    } else {
        Logging.info("The default client is already setup");
    }

    if (defaultClient && defaultClient.channel) {
        defaultClient.channel.setUseDiskRetryCaching(_isDiskRetry, _diskRetryInterval, _diskRetryMaxBytes);
    }

    return Configuration;
}

export function start() {
    if(!!defaultClient) {
        _isStarted = true;
        _console.enable(_isConsole, _isConsoleLog);
        _exceptions.enable(_isExceptions);
        _performance.enable(_isPerformance);
        _nativePerformance.enable(_isNativePerformance, _disabledExtendedMetrics);
        _serverRequests.useAutoCorrelation(_isCorrelating, _forceClsHooked);
        _serverRequests.enable(_isRequests);
        _clientRequests.enable(_isDependencies);
        if (liveMetricsClient && _isSendingLiveMetrics) {
            liveMetricsClient.enable(_isSendingLiveMetrics);
        }
    } else {
        Logging.warn("Start cannot be called before setup");
    }

    return Configuration;
}
```

Basically, there are six sets of auto collect.

- [AutoCollectConsole](https://github.com/microsoft/ApplicationInsights-node.js/blob/develop/AutoCollection/Console.ts)
- [AutoCollectExceptions](https://github.com/microsoft/ApplicationInsights-node.js/blob/develop/AutoCollection/Exceptions.ts)
- [AutoCollectPerformance](https://github.com/microsoft/ApplicationInsights-node.js/blob/develop/AutoCollection/Performance.ts)
- [AutoCollectHttpRequests](https://github.com/microsoft/ApplicationInsights-node.js/blob/develop/AutoCollection/HttpRequests.ts)
- [AutoCollectHttpDependencies](https://github.com/microsoft/ApplicationInsights-node.js/blob/develop/AutoCollection/HttpDependencies.ts)
- [AutoCollectNativePerformance](https://github.com/microsoft/ApplicationInsights-node.js/blob/master/AutoCollection/NativePerformance.ts)

The class also provides **setAutoCollectXXX** functions enable each module.
One thing to note is that "console collect" is not enabled by default and you have to explicitly enables it. I will explain this later.

Before looking into each of them, there is one environment settings I need to check.

## Enable diagnostic

According to [README](https://github.com/microsoft/ApplicationInsights-node.js/blob/develop/README.md), I can set APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL environment variable to true to enable third-party instrumentations. 

These is an **interesting bug** in Visual Studio Code which always sets the value to true. You can find the issue [here](https://github.com/microsoft/vscode/issues/75097)

So I explicitly delete the environment variable at the beginning of my code to enable the diagnostic. Don't set it false, as it only set the value as string and it never meet the if statement. Simply delete it will do the trick.

```javascript
delete process.env["APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL"];
```

# Console

In the enable function of Console, it basically enables some of **"diagnostic-channel"** modules which I can find [here](https://github.com/microsoft/ApplicationInsights-node.js/tree/develop/AutoCollection/diagnostic-channel).

This uses [Diagnostic Channel Publishers](https://github.com/microsoft/node-diagnostic-channel/tree/master/src/diagnostic-channel-publishers) which let client subscribe events.

## console.sub

[Console.sub.ts](https://github.com/microsoft/ApplicationInsights-node.js/blob/develop/AutoCollection/diagnostic-channel/console.sub.ts) collects event messages, which TelemetryClient uses trackTrace to trach them. But as I said earlier, I need to explicitly call setAutoCollectConsole function to enable this.

So I changed my code like below.

```javascript
var appInsights = require("applicationinsights");
appInsights.setup("<instrumentation_key>")
    .setAutoCollectConsole(true, true)
    .start();
```

Once I enable this, any **console.xxx** function such as **console.log()** are tracked to Application Insights.

I then added console.log to one of endpoint.

```javascript
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]
    console.log("/ was called");
    res.send(customMetric.toString());
});
```

When I execute it, then I can see the log in Application Insights.
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ry590bjhf9xsihu2u2lz.jpg)

## bunyan and winston

Simlar to console, [bunyan](https://github.com/trentm/node-bunyan) and [winston](https://github.com/winstonjs/winston) are both node.js logging library. I installed bunyan and added logger and log information in "ordersfail" endpoint.

```javascript
var bunyan = require("bunyan");
var log = bunyan.createLogger({ name: "bunynLogger" });

...
app.get("/ordersfail", (req, res) => {
    client.trackDependency({
        ...
    });
    log.info("logged in bunyan.");
    res.send("something went wrong :(");
});
```
And it logs like below.
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/kgwqyw16yb67yr58e4yi.jpg)

# Console logging : Traces and Errors

According to the [console.sub.ts](https://github.com/microsoft/ApplicationInsights-node.js/blob/develop/AutoCollection/diagnostic-channel/console.sub.ts) in develop branch, when Application Insights tracks console events, it tracks as either Trace or Exception. However when I look [console.pub.ts](https://github.com/microsoft/node-diagnostic-channel/blob/master/src/diagnostic-channel-publishers/src/console.pub.ts) publisher, it always publish the message content as string object, thus I don't know if out of box console has feature to log it as Exception. So far all the traces in my environment goes to Traces.

# Summary

It's handy to see console.log (or any other logging tool output) information in Azure Monitor for monitoring and analyzing to see how is my application doing. I can also set Alert from there when specific message is logged.

In the next article, I will explain Exception log.

[Go to next article](https://dev.to/kenakamu/application-insights-sdk-for-node-js-part-5-out-of-box-telemetries-basics-and-console-4geh)