Skip to content

Instantly share code, notes, and snippets.

@igrek8
Last active August 18, 2022 19:58
Show Gist options
  • Save igrek8/ff7fa650592430c9a77b05ee855640f8 to your computer and use it in GitHub Desktop.
Save igrek8/ff7fa650592430c9a77b05ee855640f8 to your computer and use it in GitHub Desktop.
nodejs log locator
const regex = /([^ ]+) [^(]*\(([^:]+):(\d+)/;
function getLocator() {
// stack 3
const { stack } = new Error();
if (!stack) {
return null;
}
// how far is your stdout? std write is 2 steps away
const match = stack.split(" at ")?.[3].match(regex);
if (match) {
const [, fn, file, line] = match;
return { file, fn, line };
}
return null;
}
function log(level, message, meta) {
// stack 2
const locator = getLocator();
console[level](message, { locator, meta });
}
// stack 1
log("info", "Hello World!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment