Created
January 8, 2024 15:55
-
-
Save wesbos/9b2462478e62d8633367d98c0d8d439d to your computer and use it in GitHub Desktop.
console.log line numbers in Node.js
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
// Use like this: node --import logger.js yourapp.js | |
import path from 'path'; | |
const { log } = console; | |
[`debug`, `log`, `warn`, `error`, `table`, `dir`].forEach((methodName) => { | |
const originalLoggingMethod = console[methodName]; | |
console[methodName] = (...args) => { | |
const originalPrepareStackTrace = Error.prepareStackTrace; | |
Error.prepareStackTrace = (_, stack) => stack; | |
const callee = new Error().stack[1]; | |
Error.prepareStackTrace = originalPrepareStackTrace; | |
const relativeFileName = path | |
.relative(process.cwd(), callee.getFileName()) | |
.replace(process.cwd(), ``) | |
.replace(`file:/`, ``); | |
// Log in dark grey | |
const label = `${relativeFileName}:${callee.getLineNumber()}`; | |
log(`🪵 \x1b[90m%s\x1b[0m`, label); | |
originalLoggingMethod(...args); | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome! I modified it to the following, so it'd work in more node versions (down to node 6), and then used
NODE_OPTIONS="-r 'path/to/file'"
in my shell profile so it'd be automatic, and aliased node tonode $NODE_OPTIONS
to handle node versions 1 - 5. Still haven't figured out node < 1 tho :-)