Security News
38% of CISOs Fear They’re Not Moving Fast Enough on AI
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
@0dep/pino-applicationinsights
Advanced tools
Forward pino logger to Application Insights.
Have a look in Example app to get inspiration of how to use this lib.
Ships with fake applicationinsights helper test class.
import { pino } from 'pino';
import compose from '@0dep/pino-applicationinsights';
import { Contracts } from 'applicationinsights';
const tagKeys = new Contracts.ContextTagKeys();
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',
mixin(context) {
return {
tagOverrides: {
[tagKeys.userId]: 'someUserIdPickedFromRequest',
...context.tagOverrides,
},
};
},
},
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,
},
},
},
{
level: 'debug',
target: 'pino-pretty',
options: {
colorize: true,
ignore: 'pid,hostname',
translateTime: "yyyy-mm-dd'T'HH:MM:ss.l",
},
},
],
});
const logger = pino({ level: 'trace' }, transport);
compose(opts[, TelemetryTransformation]) => Stream
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 exception
chunk
: Telemetry:ish objectconfig
: 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 TelemetryTransformationclass TelemetryTransformation(options[, config])
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 object
ignoreKeys
: 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 to Contracts.SeverityLevel
extractProperties(line, ignoreKeys)
: extract properties from log line
line
: log line record objectignoreKeys
: configured ignore keysignoreKeys
: 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 loggingclass FakeApplicationInsights(setupString)
Intercept calls to application insights.
constructor(setupString);
setupString
: Fake application insights connection stringexpectMessageData()
: Expect tracked message, returns Promise<FakeCollectData>
expectEventData()
: Expect tracked event, returns Promise<FakeCollectData>
expectExceptionData()
: Expect tracked exception, returns Promise<FakeCollectData>
expectEventType(telemetryType: string)
: Expect tracked telemetry type, returns Promise<FakeCollectData>
telemetryType
: Telemetry type stringexpect(count = 1)
: Expect tracked telemetrys, returns promise with list of FakeCollectData
count
: wait for at least tracked telemetrys before returning, default is 1reset()
: Reset expected faked Application Insights calls, calls nock.cleanAll
client
: TelemetryClient, used to get endpoint URL_endpointURL
: endpoint URL_scope
: nock Scopeimport { randomUUID } from 'node:crypto';
import 'mocha';
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();
});
});
FakeCollectData
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 under TelemetryClient.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 under TelemetryClient.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 exception
message
: error messagehasFullStack
: boolean, trueparsedStack
: stack parsed as objects[x: string]
: any other telemetry propertyiKey
: applicationinsights instrumentation keyname
: some ms name with iKey and the tracked typetime
: log time[1.1.2] - 2024-11-17
tagOverrides
FAQs
Pino applicationinsights transport
The npm package @0dep/pino-applicationinsights receives a total of 37 weekly downloads. As such, @0dep/pino-applicationinsights popularity was classified as not popular.
We found that @0dep/pino-applicationinsights demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
Research
Security News
Socket researchers uncovered a backdoored typosquat of BoltDB in the Go ecosystem, exploiting Go Module Proxy caching to persist undetected for years.
Security News
Company News
Socket is joining TC54 to help develop standards for software supply chain security, contributing to the evolution of SBOMs, CycloneDX, and Package URL specifications.