function logMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
const methodName = propertyKey;
const startTime = new Date().getTime();
console.log(`开始调用方法 ${methodName},参数为:`, args);
const result = originalMethod.apply(this, args);
if (typeof result.then === 'function') {
return result.then((res) => {
const endTime = new Date().getTime();
console.log(`方法 ${methodName} 执行完毕,耗时: ${endTime - startTime} ms`);
return res;
}).catch((err) => {
const endTime = new Date().getTime();
console.log(`方法 ${methodName} 执行出错,耗时: ${endTime - startTime} ms`);
throw err;
});
} else {
const endTime = new Date().getTime();
console.log(`方法 ${methodName} 执行完毕,耗时: ${endTime - startTime} ms`);
return result;
}
};
return descriptor;
}
class MyClass {
@logMethod
async asyncMethod(param1: string, param2: number) {
await new Promise(resolve => setTimeout(resolve, 1000));
return `Async result: ${param1} - ${param2}`;
}
@logMethod
syncMethod(param1: string, param2: number) {
return `Sync result: ${param1} - ${param2}`;
}
}
const myObj = new MyClass();
myObj.asyncMethod('test', 123).then(console.log);
console.log(myObj.syncMethod('test', 456));