Skip to content

Instantly share code, notes, and snippets.

@DV8FromTheWorld
Last active December 30, 2019 21:01
Show Gist options
  • Save DV8FromTheWorld/9fdcf243808e378300b463736e2ae158 to your computer and use it in GitHub Desktop.
Save DV8FromTheWorld/9fdcf243808e378300b463736e2ae158 to your computer and use it in GitHub Desktop.
Instrument node callback functions
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