Skip to content

Commit 6c42f14

Browse files
pass merging object to mixins (pinojs#926)
* pass merging object to mixins * add tests for passing mixin context * improve mixin context tests * add usage of mixin argument to documentation
1 parent e4be7f8 commit 6c42f14

File tree

3 files changed

+37
-4
lines changed

3 files changed

+37
-4
lines changed

docs/api.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ logger.info('hello') // Will throw an error saying info in not found in logger o
9999
Default: `undefined`
100100

101101
If provided, the `mixin` function is called each time one of the active
102-
logging methods is called. The function must synchronously return an
102+
logging methods is called. The first and only parameter is the value `mergeObject` or an empty object. The function must synchronously return an
103103
object. The properties of the returned object will be added to the
104104
logged JSON.
105105

@@ -124,7 +124,7 @@ const mixin = {
124124
}
125125

126126
const logger = pino({
127-
mixin() {
127+
mixin({ description }) {
128128
return mixin
129129
}
130130
})

lib/proto.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -147,9 +147,9 @@ function write (_obj, msg, num) {
147147
var obj
148148

149149
if (_obj === undefined || _obj === null) {
150-
obj = mixin ? mixin() : {}
150+
obj = mixin ? mixin({}) : {}
151151
} else {
152-
obj = Object.assign(mixin ? mixin() : {}, _obj)
152+
obj = Object.assign(mixin ? mixin(_obj) : {}, _obj)
153153
if (!msg && objError) {
154154
msg = _obj.message
155155
}

test/mixin.test.js

+33
Original file line numberDiff line numberDiff line change
@@ -101,3 +101,36 @@ test('mixin not a function', async ({ throws }) => {
101101
pino({ mixin: 'not a function' }, stream)
102102
})
103103
})
104+
105+
test('mixin can use context', async ({ ok }) => {
106+
const stream = sink()
107+
const instance = pino({
108+
mixin (context) {
109+
ok(context !== null && context !== undefined, 'context should be defined')
110+
return Object.assign({
111+
error: context.message,
112+
stack: context.stack
113+
})
114+
}
115+
}, stream)
116+
instance.level = name
117+
instance[name]({
118+
message: '123',
119+
stack: 'stack'
120+
}, 'test')
121+
})
122+
123+
test('mixin works without context', async ({ ok }) => {
124+
const stream = sink()
125+
const instance = pino({
126+
mixin (context) {
127+
ok(context !== null && context !== undefined, 'context is still defined w/o passing mergeObject')
128+
129+
return {
130+
something: true
131+
}
132+
}
133+
}, stream)
134+
instance.level = name
135+
instance[name]('test')
136+
})

0 commit comments

Comments
 (0)