DEV Community

Gaëtan Redin
Gaëtan Redin

Posted on • Originally published at Medium on

2 2

Logger decorator

Typescript method decorator

Hey, often we make console.log(...) to see the value of a parameter or a result method.

Here I present you a decorator which allow to do it easily. It’s purpose is for debugging when you are developing something.

interface LoggerParams {
type?: 'log' | 'trace' | 'warn' | 'info' | 'debug';
inputs?: boolean;
outputs?: boolean;
}
const defaultParams: Required<LoggerParams> = {
type: 'debug',
inputs: true,
outputs: true,
};
export function Log(params?: LoggerParams) {
const options: Required<LoggerParams> = {
type: params?.type || defaultParams.type,
inputs: params?.inputs === undefined ? defaultParams.inputs : params.inputs,
outputs: params?.outputs === undefined ? defaultParams.outputs : params.outputs,
};
return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function(...args: any[]) {
if (options.inputs) {
console[options.type]('Logged inputs:', args);
}
const result = original.apply(this, args);
if (options.outputs) {
console[options.type]('Logged outputs', result);
}
return result;
};
};
}

Now that’s how to use it:

class Toto {
  @Log()
  public myMethod(...args: unknown[]): boolean { ... }

  @Log({ outputs: false })
  public myMethod2(...args: unknown[]): void { ... }

  @Log({ inputs: false })
  public myMethod3(...args: unknown[]): unknown { ... }

  @Log({ type: 'trace' })
  public myMethod4(...args: unknown[]): unknown { ... }

  @Log({ type: 'trace', inputs: false, outputs: false })
  public myMethod5(...args: unknown[]): unknown { ... }

}
Enter fullscreen mode Exit fullscreen mode

Hope this could help or inspire someone.

Thanks for reading, feel free to comment.

Learn More

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (1)

Collapse
 
nombrekeff profile image
Keff

Great stuff! I did something similar on an old angular project. But made it so it would only log stuff on development

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay