I want to write a log decorator that logs every time the function (in which the decorator decorates) is called. I want to log a key that the decorator accepts as a parameter and the arguments that the function was sent with.
So far I know how to write a simple log function that logs the function arguments but cant accept any parameters:
export function logger(
target: Object,
key: string,
descriptor: PropertyDescriptor
) {
const original = descriptor.value;
descriptor.value = function() {
const targetName = target.constructor.name;
const args = JSON.stringify(arguments);
console.log(`Calling ${targetName}.${key} with ${JSON.stringify(arguments)}`);
const result = original.apply(this, arguments);
return result;
};
return descriptor;
}
I also know how to write a decorator that accepts parameters:
log(logData: { value: string; target?: string }) {
return function(
target: Object,
key: string,
descriptor: PropertyDescriptor
) {
console.log(`Key: ${logData.value}, Target: ${logData.target}`);
};
}
So you probably can guess that I am missing a link here which is to write a log decorator that can accepts a key as a parameter and logs this key with the arguments that the decorated function was called with.
I have a working example of those 2 decorators here:
https://stackblitz.com/edit/angular-udi-decorators?file=src%2Fapp%2Flogger.ts