/winston-azure-application-insights

Azure Application Insights transport for Winston

Primary LanguageJavaScriptMIT LicenseMIT

winston-azure-application-insights

An Azure Application Insights transport for Winston logging library. Allows to log on App Insights trace with Winston.

This library intends to be compatible with applicationinsights 1.0. If you are using an older version of the AppInsights NodeJS client, see the 1.1.x releases.

Installation

Tested on node-5.10.x, requires npm.

  $ npm install winston
  $ npm install winston-azure-application-insights

Usage

See demo.js for a small example.

Instrumentation key

Note: an instrumentation key is required before any data can be sent. Please see the "Getting an Application Insights Instrumentation Key" for more information.

The instrumentation key can be supplied in 4 ways:

  • Specifying the "key" property in the options of the transport:
var aiLogger = require('winston-azure-application-insights').AzureApplicationInsightsLogger;

// Create an app insights client with the given key
winston.add(aiLogger, {
	key: "<YOUR_INSTRUMENTATION_KEY_HERE>"
});
  • Passing an initialized Application Insights module reference in the "insights" options property (This may be useful if you want to configure AI to suit your needs):
var appInsights = require("applicationinsights"),
	aiLogger = require('winston-azure-application-insights').AzureApplicationInsightsLogger;

appInsights.setup("<YOUR_INSTRUMENTATION_KEY_HERE>").start();

// Use an existing app insights SDK instance
winston.add(aiLogger, {
	insights: appInsights
});
  • Passing an initialized Application Insights client in the "client" options property:
var appInsights = require("applicationinsights"),
	aiLogger = require('winston-azure-application-insights').AzureApplicationInsightsLogger;

appInsights.setup("<YOUR_INSTRUMENTATION_KEY_HERE>").start();

// Create a new app insights client with another key
winston.add(aiLogger, {
	client: appInsights.getClient("<ANOTHER_INSTRUMENTATION_KEY_HERE>")
});
  • Setting the APPINSIGHTS_INSTRUMENTATIONKEY environment variable (supported by the Application Insights SDK)

I get an error when using this transport

If you receive the error:

"Instrumentation key not found, pass the key in the config to this method or set the key in the environment variable APPINSIGHTS_INSTRUMENTATIONKEY before starting the server"

Then you didn't specify a suitable instrumentation key. See the section above.

I get an error "Zones already loaded"

Quick fix: upgrade to applicationinsights@1.0.2

If you cannot upgrade, read on:

This may be because your environment has implicitly loaded applicationinsights and called .setup(). This happens if you are running an Azure Function App and have APPINSIGHTS_INSTRUMENTATIONKEY set. The best solution to this is to load applicationinsights and pass in appInsights.defaultClient using the client option as per example 3.

Options

  • level: lowest logging level transport to be logged (default: info)
  • silent: Boolean flag indicating whether to suppress output (default: false)
  • treatErrorsAsExceptions: Boolean flag indicating whether to treat errors as exceptions. See section below for more details (default: false).
  • formatter: format and mutate arguments passed to applicationinsights track* methods with a signature of trackMethodName, userLevel, options (default: noop)

SDK integration options (required):

Ony one of the above option parameters will be used, in this order: client, insights, key.

  • client: An existing App Insights client
  • insights: An App Insights SDK instance (needs to be already started)
  • key: App Insights instrumentation key. An instance of the SDK will be initialized and started using this key. In lieu of this setting, you can set the environment variable: APPINSIGHTS_INSTRUMENTATIONKEY

Log Levels

Supported log levels are:

Winston Level App Insights level
emerg critical (4)
alert critical (4)
crit critical (4)
error error (3)
warning warning (2)
warn warning (2)
notice informational (1)
info informational (1)
verbose verbose (0)
debug verbose (0)
silly verbose (0)

All other possibile Winston's levels, or custom levels, will default to info

Treating errors as exceptions

You can set the option treatErrorsAsExceptions when configuring the transport to treat errors as app insights exceptions for log levels >= error (defaults to false).

This allows you to see it clearly in the Azure Application Insights instead of having to access trace information manually and set up alerts based on the related metrics.

How it works:

  • winstonLogger.log('error', 'error message'); will trigger an app insights trackException with Error('error message') as argument

  • winstonLogger.log('error', new Error('error message')); will trigger an app insights trackException with the Error object as argument

  • winstonLogger.log('error', 'error message', new Error('error message')); will trigger an app insights trackException with the Error object as argument

Formatter

You can specify a formatter option to override the objects passed to trackTrace or trackException. This is an easy way to add some "global" context to your logging, and follows the formatter pattern used in other Winston transports.

If you want to enhance the default formatting functionality then the defaultFormatter is exposed, too.

var aiWinstonPackage = require('winston-azure-application-insights');
var AzureApplicationInsightsLogger = aiWinstonPackage.AzureApplicationInsightsLogger;
var defaultFormatter = aiWinstonPackage.defaultFormatter;

winston.add(AzureApplicationInsightsLogger, {
	// override the formatter to add the app version to the property metadata:
	formatter: function addAppVersion(traceOrException, userLevel, options) {
		var props = options.properties || {};
		// add "myAppVersion" from env:
		var formattedProps = Object.assign({}, props, {
			myAppVersion: process.env.MY_APP_VERSION,
		});
		// pass back to defaultFormatter:
		return defaultFormatter(
			traceOrException,
			userLevel,
			// make changes to properties:
			Object.assign({}, options, {
				properties: formattedProps,
			})
		);
	}
});