How to Use Decorators to Print Log in Typescript
- creat a decorator:
function logDecorator(target: any, propertyName: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args) {
console.log(`Calling begin ${propertyName} with args: ${args}`);
const startTime = new Date().getTime();
const result = originalMethod.apply(this, args);
const endTime = new Date().getTime();
console.log(`Calling end ${propertyName}. used ${endTime - startTime}ms`);
return result;
};
}
- use this decorator
class MyClass {
@logDecorator
myMethod(arg1: string, arg2: number) {
return `${arg1} - ${arg2}`;
}
}
const myInstance = new MyClass();
myInstance.myMethod("Hello", 123);
full code:
function logDecorator(target: any, propertyName: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args) {
console.log(`Calling begin ${propertyName} with args: ${args}`);
const startTime = new Date().getTime();
const result = originalMethod.apply(this, args);
const endTime = new Date().getTime();
console.log(`Calling end ${propertyName}. used ${endTime - startTime}ms`);
return result;
};
}
class MyClass {
@logDecorator
myMethod(arg1: string, arg2: number) {
return `${arg1} - ${arg2}`;
}
}
const myInstance = new MyClass();
myInstance.myMethod("Hello", 123);
console print log:
Calling begin myMethod with args: Hello,123
Calling end myMethod. used 0ms