passing logger methods to a function (2)
Closed this issue · 4 comments
I cannot come up with a solution to extract pino's logging methods.
I found a few issues here, discussing this one, but I cannot successfully bind this
.
Example 1: using a single method:
const logger = pino();
const info = logger.info
logger.info.bind(logger)
info('test')
Error:
/home/runner/PinoBind/node_modules/pino/lib/tools.js:68
if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {
^
TypeError: Cannot read properties of undefined (reading 'Symbol(pino.msgPrefix)')
at LOG (/home/runner/PinoBind/node_modules/pino/lib/tools.js:68:22)
Sandbox: https://replit.com/@OnkelTem/PinoBind#index.js
Example 2: using an object with methods:
const logger = pino();
const methods = {
info: logger.info
}
logger.info.bind(logger)
methods.info('test')
Error:
/home/runner/PinoBind/node_modules/pino/lib/tools.js:71
this[writeSym](null, format(msg, n, this[formatOptsSym]), level)
^
TypeError: this[writeSym] is not a function
at Object.LOG [as info] (/home/runner/PinoBind/node_modules/pino/lib/tools.js:71:21)
const logger = pino();
const info = logger.info
logger.info.bind(logger)
info('test')
You have assigned the bound function to nothing and then used the unbound function to log the string 'test'
.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
Answering to myself.
bind()
isn't mutating, it returns a new thing.
So the correct variants are:
const logger = pino();
const info = logger.info.bind(logger)
info('test')
const logger = pino();
const methods = {
info: logger.info.bind(logger)
}
methods.info('test')
Sandbox: https://replit.com/@OnkelTem/PinoBind2
Surprisingly, this was overlooked in previous answers.
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.