Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(mixin): add mixin config option #741

Merged
merged 4 commits into from
Nov 21, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,27 @@ logger.foo('hi')
logger.info('hello') // Will throw an error saying info in not found in logger object
```

#### `mixin` (Function):

Default: `undefined`

If provided, the `mixin` function is called each time one of the active
logging methods is called. The function must return an object. The
properties of the returned object will be added to the logged JSON.

```js
let n = 0
const logger = pino({
mixin () {
return { line: ++n }
}
})
logger.info('hello')
// {"level":30,"time":1573664685466,"pid":78742,"hostname":"x","line":1,"msg":"hello","v":1}
logger.info('world')
// {"level":30,"time":1573664685469,"pid":78742,"hostname":"x","line":2,"msg":"hello","v":1}
```

#### `redact` (Array | Object):

Default: `undefined`
Expand Down
6 changes: 4 additions & 2 deletions lib/proto.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const {
setLevelSym,
getLevelSym,
chindingsSym,
mixinSym,
asJsonSym,
messageKeySym,
writeSym,
Expand Down Expand Up @@ -115,14 +116,15 @@ function bindings () {
function write (_obj, msg, num) {
const t = this[timeSym]()
const messageKey = this[messageKeySym]
const mixin = this[mixinSym]
const objError = _obj instanceof Error
var obj

if (_obj === undefined || _obj === null) {
obj = {}
obj = mixin ? mixin() : {}
obj[messageKey] = msg
} else {
obj = Object.assign({}, _obj)
obj = Object.assign(mixin ? mixin() : {}, _obj)
if (msg) {
obj[messageKey] = msg
} else if (objError) {
Expand Down
2 changes: 2 additions & 0 deletions lib/symbols.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const levelValSym = Symbol('pino.levelVal')
const useLevelLabelsSym = Symbol('pino.useLevelLabels')
const changeLevelNameSym = Symbol('pino.changeLevelName')
const useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels')
const mixinSym = Symbol('pino.mixin')

const lsCacheSym = Symbol('pino.lsCache')
const chindingsSym = Symbol('pino.chindings')
Expand Down Expand Up @@ -37,6 +38,7 @@ module.exports = {
getLevelSym,
levelValSym,
useLevelLabelsSym,
mixinSym,
lsCacheSym,
chindingsSym,
parsedChindingsSym,
Expand Down
4 changes: 4 additions & 0 deletions pino.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const {
messageKeySym,
useLevelLabelsSym,
changeLevelNameSym,
mixinSym,
useOnlyCustomLevelsSym
} = symbols
const { epochTime, nullTime } = time
Expand Down Expand Up @@ -71,6 +72,7 @@ function pino (...args) {
customLevels,
useLevelLabels,
changeLevelName,
mixin,
useOnlyCustomLevels
} = opts

Expand All @@ -92,6 +94,7 @@ function pino (...args) {
const timeSliceIndex = time().indexOf(':') + 1

if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true')
if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type "${typeof mixin}" - expected "function"`)

assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels)
const levels = mappings(customLevels, useOnlyCustomLevels)
Expand All @@ -110,6 +113,7 @@ function pino (...args) {
[formatOptsSym]: formatOpts,
[messageKeySym]: messageKey,
[serializersSym]: serializers,
[mixinSym]: mixin,
[chindingsSym]: chindings
}
Object.setPrototypeOf(instance, proto)
Expand Down
106 changes: 106 additions & 0 deletions test/mixin.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
'use strict'

const os = require('os')
const { test } = require('tap')
const { sink, once } = require('./helper')
const pino = require('../')

const { pid } = process
const hostname = os.hostname()
const level = 50
const name = 'error'

test('mixin object is included', async ({ ok, same }) => {
let n = 0
const stream = sink()
const instance = pino({
mixin () {
return { hello: ++n }
}
}, stream)
instance.level = name
instance[name]('test')
const result = await once(stream, 'data')
ok(new Date(result.time) <= new Date(), 'time is greater than Date.now()')
delete result.time
same(result, {
pid,
hostname,
level,
msg: 'test',
hello: 1,
v: 1
})
})

test('mixin object is new every time', async ({ plan, ok, same }) => {
plan(6)

let n = 0
const stream = sink()
const instance = pino({
mixin () {
return { hello: n }
}
}, stream)
instance.level = name

while (++n < 4) {
const msg = `test #${n}`
stream.pause()
instance[name](msg)
stream.resume()
const result = await once(stream, 'data')
ok(new Date(result.time) <= new Date(), 'time is greater than Date.now()')
delete result.time
same(result, {
pid,
hostname,
level,
msg,
hello: n,
v: 1
})
}
})

test('mixin object is not called if below log level', async ({ ok }) => {
const stream = sink()
const instance = pino({
mixin () {
ok(false, 'should not call mixin function')
}
}, stream)
instance.level = 'error'
instance.info('test')
})

test('mixin object + logged object', async ({ ok, same }) => {
let n = 0
const stream = sink()
const instance = pino({
mixin () {
return { hello: ++n }
}
}, stream)
instance.level = name
instance[name]({ foo: 42 })
const result = await once(stream, 'data')
ok(new Date(result.time) <= new Date(), 'time is greater than Date.now()')
delete result.time
same(result, {
pid,
hostname,
level,
foo: 42,
hello: 1,
v: 1
})
})

test('mixin not a function', async ({ throws }) => {
const stream = sink()
throws(function () {
pino({ mixin: 'not a function' }, stream)
})
})