averainy's Blog

averainy

29 May 2024

How to Use Decorators to Print Log in Typescript

  1. 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;
  };
}
  1. 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