Skip to content

Instantly share code, notes, and snippets.

@mikesmullin
Created November 24, 2017 23:21
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mikesmullin/008721d4753d3e0d9a95cda617874736 to your computer and use it in GitHub Desktop.
Save mikesmullin/008721d4753d3e0d9a95cda617874736 to your computer and use it in GitHub Desktop.
Node.JS print filename and line number prefixed to console log output
const path = require('path');
function trace(s) {
const orig = Error.prepareStackTrace;
Error.prepareStackTrace = (_, stack) => stack;
const err = new Error();
Error.captureStackTrace(err, arguments.callee);
Error.prepareStackTrace = orig;
const callee = err.stack[0];
process.stdout.write(`${path.relative(process.cwd(), callee.getFileName())}:${callee.getLineNumber()}: ${s}\n`);
}
module.exports = trace;
trace("hey");
@juanMarinero
Copy link

KasparEtter customized console.log() thanks in part to ( "Inspired by" quoting him) code in this GitHub, so I think it's relevant to show its solution: https://stackoverflow.com/a/60305881/9391770
I find his solution amazing!

@jorgeoliveirasantos
Copy link

let x = new Error().stack.split("\n")[1];
console.log(x);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment