To streamline the logging process for the invocation of methods like myMethod
and others in a more abstract manner (considered a cross-cutting concern), you can utilize a decorator:
function log<A extends any[], R>(
target: Object,
methodName: string,
descriptor: TypedPropertyDescriptor<(...args: A) => R>) {
let method = descriptor.value!; // this is the wrapped function
descriptor.value = function (...args: A) {
// method.name can also be used instead of methodName to retrieve the method's name
console.log("Calling", methodName, "with", args, "from", target.constructor.name)
return method.apply(target, args);
}
}
class MyClass {
@log
public myMethod() { }
@log
public myMethod2(s: string) { return 42 }
}
new MyClass().myMethod() // Calling myMethod with Array [] from MyClass
new MyClass().myMethod2("foo") // Calling myMethod2 with Array [ "foo" ] from MyClass
Check out a demo. Please note that this functionality is still in development and must be enabled using the experimentalDecorators
compiler option.