Last active
August 18, 2022 19:58
-
-
Save igrek8/ff7fa650592430c9a77b05ee855640f8 to your computer and use it in GitHub Desktop.
nodejs log locator
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
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