Created
July 24, 2020 04:44
-
-
Save MilllerTime/c38f8b298321b9ce089ec12f0d8f734b to your computer and use it in GitHub Desktop.
Augments all methods on a given object to log a message to the console when called.
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
/** | |
* Augments all methods on a given object to log a message to the console when called. | |
* Useful for understanding how objects are used during an application's lifecycle. | |
* | |
* @param {string} baseName Logged as the indentifer before called method names. | |
* @param {object} target The object with methods that should be monitored for calls. | |
* | |
* @return {object} Returns the modified target object. | |
*/ | |
function logMethodCalls(baseName, target) { | |
for (const key of Object.keys(target)) { | |
const value = target[key]; | |
// We only care about function properties... | |
if (typeof value === 'function') { | |
// Create a new function to replace the original method, that behaves identitically to the original function | |
// except it logs a message to the console when called. | |
function logger(...args) { | |
console.log( | |
`%cMETHOD CALL%c ${baseName}.${key}()`, | |
'color: #fff; background-color: #07C; padding: 1px 6px; border-radius: 2px', | |
'color: #07C;' | |
); | |
// Ensure the correct `this` value and all arguments are pass through to original function. | |
// Also ensure our wrapper returns any value returned by the original function. | |
return value.apply(this, args); | |
} | |
// Make this wrapper function obvious in call stacks. | |
logger.name = `logger(${value.name})`; | |
target[key] = logger; | |
} | |
} | |
return target; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment