-
-
Save tung1404/4854b5aea1ab3d0792ae45ce63705ed0 to your computer and use it in GitHub Desktop.
Node.js pino logger show caller filename and line number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import path from 'path' | |
import pino from 'pino' | |
const STACKTRACE_OFFSET = 2 | |
const LINE_OFFSET = 7 | |
const { symbols : { asJsonSym} } = pino | |
function traceCaller (pinoInstance) { | |
const get = (target, name) => name === asJsonSym ? asJson : target[name] | |
function asJson (...args) { | |
args[0] = args[0] || Object.create(null) | |
args[0].caller = Error().stack.split('\n').filter(s => !s.includes('node_modules/pino') && !s.includes('node_modules\\pino'))[STACKTRACE_OFFSET].substr(LINE_OFFSET).replace(path.resolve(__dirname, '..'), '') | |
return pinoInstance[asJsonSym].apply(this, args) | |
} | |
return new Proxy(pinoInstance, { get }) | |
} | |
const logger = traceCaller(pino({ | |
level: 'debug', | |
prettyPrint: { | |
colorize: true, | |
} | |
})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment