Last active
December 30, 2019 21:01
-
-
Save DV8FromTheWorld/9fdcf243808e378300b463736e2ae158 to your computer and use it in GitHub Desktop.
Instrument node callback functions
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
const generateId = () => Math.random().toString(36).substring(2, 8) + Math.random().toString(36).substring(2, 8) | |
function instrumentFunction(name, originalFn, cbPosition = 0) { | |
return function enhancedFunction(...args) { | |
const ident = generateId() | |
const callerLine = `(${new Error().stack.split('\n')[2].trim()})` | |
const enhancedCB = function (...cbArgs) { | |
console.log(`${ident}: ${name} starting ${callerLine}`) | |
try { | |
args[cbPosition].bind(this)(...cbArgs) | |
} | |
finally { | |
console.log(`${ident}: ${name} complete ${callerLine}`) | |
} | |
} | |
const newArgs = [...args] | |
newArgs[cbPosition] = enhancedCB | |
console.log(`${ident}: ${name} registered ${callerLine}`) | |
return originalFn.apply(this, newArgs) | |
} | |
} | |
const { ClientRequest, IncomingMessage } = require('http') | |
ClientRequest.prototype.on = instrumentFunction('ClientRequest.on', ClientRequest.prototype.on, 1) | |
ClientRequest.prototype.once = instrumentFunction('ClientRequest.once', ClientRequest.prototype.once, 1) | |
IncomingMessage.prototype.on = instrumentFunction('IncomingMessage.on', IncomingMessage.prototype.on, 1) | |
IncomingMessage.prototype.once = instrumentFunction('IncomingMessage.once', IncomingMessage.prototype.once, 1) | |
setTimeout = instrumentFunction('setTimeout', setTimeout) | |
setInterval = instrumentFunction('setInterval', setInterval) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment