Last active
February 7, 2019 05:23
-
-
Save iyobo/3d9eb2237e5bde69b3734398fcfc2b95 to your computer and use it in GitHub Desktop.
Hijacks your normal boring NodeJS console.log and gives it powers.
This file contains hidden or 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
export const initLogger = ()=>{ | |
['log', 'warn', 'error'].forEach((methodName) => { | |
const originalMethod = console[methodName]; | |
console[methodName] = (...args) => { | |
let initiator = 'unknown place'; | |
const timestamp = new Date().toISOString(); | |
try { | |
throw new Error(); | |
} catch (e) { | |
if (typeof e.stack === 'string') { | |
let isFirst = true; | |
for (const line of e.stack.split('\n')) { | |
const matches = line.match(/^\s+at\s+(.*)/); | |
if (matches) { | |
if (!isFirst) { // first line - current function | |
// second line - caller (what we are looking for) | |
initiator = matches[1]; | |
break; | |
} | |
isFirst = false; | |
} | |
} | |
} | |
} | |
originalMethod.apply(console, [...args, '\n', ` ${timestamp} at ${initiator}`]); | |
}; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment