Forward pino logger to Application Insights.
Ships with fake applicationinsights helper test class.
import { pino } from 'pino';
import compose from '@0dep/pino-applicationinsights';
const transport = compose({
track(chunk) {
const { time, severity, msg: message, properties, exception } = chunk;
this.trackTrace({ time, severity, message, properties });
if (exception) this.trackException({ time, exception, severity });
},
connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING,
config: { maxBatchSize: 1 },
});
const logger = pino({ level: 'trace' }, transport);
or as multi transport:
import { pino } from 'pino';
const transport = pino.transport({
targets: [
{
level: 'info',
target: '@0dep/pino-applicationinsights',
options: {
connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING,
config: {
disableStatsbeat: true,
},
},
},
],
});
const logger = pino(transport);
Build transport stream function.
opts
:connectionString
: Application Insights connection string or instrumentation keytrack(chunk)
: optional track function called with Telemetry client context, defaults to tracking trace and exceptionchunk
: Telemetry:ish object
config
: optional Application Insights Telemetry client configdestination
: optional destination stream, makes compose ignore the above optionsignoreKeys
: optional pino ignore keys, used to filter telemetry properties, defaults to['hostname', 'pid', 'level', 'time', 'msg']
TelemetryTransformation
: optional transformation stream extending TelemetryTransformation
Telemetry transformation stream. Transforms pino log record to Telemetry:ish object.
constructor(options[, config])
options
: transform stream options,{ objectMode: true }
is always setconfig
: optional config objectignoreKeys
: optional pino ignore keys as string array
_transform(chunk, encoding, callback)
convertToTelemetry(chunk)
: convert pino log record string or object to telemetry:ish objectconvertLevel(level)
: map pino log level number toContracts.SeverityLevel
extractProperties(line, ignoreKeys)
: extract properties from log lineline
: log line record objectignoreKeys
: configured ignore keys
- properties:
ignoreKeys
: configured ignore keys, defaults to['hostname', 'pid', 'level', 'time', 'msg']
severity
: pino log level mapped to application insights severeity level, i.e.Contracts.SeverityLevel
msg
: log message stringproperties
: telemetry properties object, filtered through ignore keysexception?
: logged Error if any[k: string]
: any other properties that facilitate telemetry logging
Intercept calls to application insights.
constructor(setupString);
setupString
: Fake application insights connection string
expectMessageData()
: Expect tracked message, returnsPromise<FakeCollectData>
expectEventData()
: Expect tracked event, returnsPromise<FakeCollectData>
expectExceptionData()
: Expect tracked exception, returnsPromise<FakeCollectData>
expectEventType(telemetryType: string)
: Expect tracked telemetry type, returnsPromise<FakeCollectData>
telemetryType
: Telemetry type string
expect(count = 1)
: Expect tracked telemetrys, returns promise with list ofFakeCollectData
count
: wait for at least tracked telemetrys before returning, default is 1
reset()
: Reset expected faked Application Insights calls, callsnock.cleanAll
- properties:
client
: TelemetryClient, used to get endpoint URL_endpointURL
: endpoint URL_scope
: nock Scope
import { describe } from 'mocha';
import { randomUUID } from 'node:crypto';
import { pino } from 'pino';
import compose from '@0dep/pino-applicationinsights';
import { FakeApplicationInsights } from '@0dep/pino-applicationinsights/fake-applicationinsights';
describe('test logger', () => {
const connectionString = `InstrumentationKey=${randomUUID()};IngestionEndpoint=https://ingestion.local;LiveEndpoint=https://livemonitor.local/`;
let fakeAI;
before(() => {
fakeAI = new FakeApplicationInsights(connectionString);
});
after(() => {
fakeAI.reset();
});
it('log event track event', async () => {
const transport = compose({
track(chunk) {
const { time, properties } = chunk;
this.trackEvent({ name: 'my event', time, properties, measurements: { logins: 1 } });
},
connectionString,
config: { maxBatchSize: 1, disableStatsbeat: true },
});
const logger = pino(transport);
const expectMessage = fakeAI.expectEventData();
logger.info({ bar: 'baz' }, 'foo');
const msg = await expectMessage;
expect(msg.body.data.baseData).to.deep.include({
properties: { bar: 'baz' },
measurements: { logins: 1 },
name: 'my event',
});
transport.destroy();
});
});
An object representing the request sent to application insights.
uri
: request urimethod
: request methodheaders
: request headers objectbody
:ver
: some version number, usually 1sampleRate
: sample rate number, usually 100tags
: object with tags, tag names can be inspected underTelemetryClient.context.keys
, e.g:ai.application.ver
: your package.json versionai.device.id
: ?ai.cloud.roleInstance
: computer hostname?ai.device.osVersion
: computer osai.cloud.role
: Web maybe?ai.device.osArchitecture
: probably x64ai.device.osPlatform
: os platform, as the name saysai.internal.sdkVersion
: applicationinsights package version, e.g.node:2.9.1
[tag name]
: any other tag found underTelemetryClient.context.keys
data
:baseType
: telemetry type stringbaseData
:ver
: some version number, usually 2 for some reasonproperties
: telemetry properties object[message]
: logged message when tracking trace[severityLevel]
: applicationinsights severity level number when tracking trace and exception[exceptions]
: list of exceptions when tracking exceptionmessage
: error messagehasFullStack
: boolean, trueparsedStack
: stack parsed as objects
[x: string]
: any other telemetry property
iKey
: applicationinsights instrumentation keyname
: some ms name with iKey and the tracked typetime
: log time