chengaofeng
发布于 2024-07-11 / 10 阅读
0
0

TypeScript装饰器应用场景:日志记录

写一个装饰器自动记录类的方法调用信息,包括参数、返回值和执行时间,有助于调试和监控应用行为。

以下是一个使用TypeScript装饰器来实现日志记录功能的示例。这个装饰器会自动记录任何被装饰方法的调用信息,包括方法名、传入的参数、返回值以及方法的执行时间。

首先,定义一个方法装饰器Log

function Log(target: any, propertyName: string, propertyDesciptor: PropertyDescriptor): PropertyDescriptor {

  const method = propertyDesciptor.value;

  propertyDesciptor.value = function (...args: any[]) {

    const startTime = performance.now();

    const result = method.apply(this, args);

    const endTime = performance.now();

    console.log(`调用方法: ${propertyName}`);

    console.log(`传入参数: ${JSON.stringify(args)}`);

    console.log(`返回结果: ${JSON.stringify(result)}`);

    console.log(`执行时间: ${(endTime - startTime).toFixed(2)}ms`);

    return result;

  };

  return propertyDesciptor;

}

然后,使用@Log装饰器来装饰类的方法:

class ExampleClass {

  @Log

  someMethod(arg1: number, arg2: string) {

    console.log(`方法内部逻辑被执行: ${arg1}, ${arg2}`);

    return 结果: ${arg1}, ${arg2};

  }

}

最后,创建ExampleClass的实例并调用被装饰的方法:

const example = new ExampleClass();

example.someMethod(123, 'abc');

当调用someMethod方法时,装饰器Log会自动记录方法的调用信息,包括方法名、传入的参数、返回值以及方法的执行时间,并通过console.log输出到控制台。

这个示例展示了如何使用装饰器来增强类的方法,实现自动的日志记录功能,有助于调试和监控应用行为。


评论