Last active
December 21, 2023 16:19
-
-
Save TwitchBronBron/9f34217b56e9c47d1116cdf6119a2444 to your computer and use it in GitHub Desktop.
TrackDuration
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
let durationSequence = 1; | |
function TrackDuration(options?: { enabled?: boolean; excludes?: Array<string> }) { | |
return function TrackDuration(target: any, propertyKey?: string, descriptor?: PropertyDescriptor) { | |
if (options?.enabled === false) { | |
return; | |
} | |
let methods: any[]; | |
//is a method | |
if (propertyKey) { | |
methods.push(propertyKey); | |
//is a class | |
} else { | |
methods = Object.getOwnPropertyNames(target.prototype); | |
} | |
const excludes = options?.excludes ?? []; | |
//filter out any excluded methods | |
methods = methods.filter(x => !excludes.includes(x)); | |
methods.forEach((methodName) => { | |
const originalMethod = target.prototype[methodName]; | |
//skip non-functions | |
if (typeof originalMethod !== 'function') { | |
return; | |
} | |
target.prototype[methodName] = function executeFunctionWrapped(...args: any[]) { | |
let logger = this.logger instanceof Logger ? this.logger : console; | |
const start = Date.now(); | |
let result; | |
const seq = durationSequence++; | |
try { | |
logger.log(`req-${seq} ${methodName} begin`); | |
result = originalMethod.apply(this, args); | |
return result; | |
} finally { | |
Promise.resolve(result).finally(() => { | |
logger.log(`req-${seq} ${methodName} end (${Date.now() - start}ms)`); | |
}); | |
} | |
}; | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an annotation to track the duration of a function. it prints out how long the method took to run.