Skip to content

Instantly share code, notes, and snippets.

@TwitchBronBron
Last active December 21, 2023 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TwitchBronBron/9f34217b56e9c47d1116cdf6119a2444 to your computer and use it in GitHub Desktop.
Save TwitchBronBron/9f34217b56e9c47d1116cdf6119a2444 to your computer and use it in GitHub Desktop.
TrackDuration
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)`);
});
}
};
});
};
}
@TwitchBronBron
Copy link
Author

This is an annotation to track the duration of a function. it prints out how long the method took to run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment