I print many logs in the static method and I want to use the method name as context. But I don't want to declare a context
variable and assign the function/method name to it.
I want to use the context by accessing the method name. Not only in a class static method, but also in every function.
Here is my try:
class CloudFunction {
public static parse() {
console.log(this.name); // CloudFunction
console.log(CloudFunction.parse.name); // get nothing here
// Don't want to declare `context` variable and assign method name to it.
const context = 'parse';
logger.debug('a log', { context, arguments: 'pubsubMessage' });
//... many logs use this context
// want the better way like this:
// const self = this;
// logger.error(new Error('bad'), {context: self.name })
}
}
CloudFunction.parse();
None of them work. Can I use reflect
way to get it? I am not sure reflect
can do this.
update
Here is my result:
☁ DL-Toolkits [master] npx ts-node /Users/ldu020/workspace/github.com/mrdulin/ts-codelab/src/class/get-static-method-name/index.ts
CloudFunction
I am getting the name of the method, or do I misunderstand anything?
class ClassWithStaticMethod {
static staticMethod() {
console.log('1: ' + ClassWithStaticMethod.staticMethod.name); // output: '1: staticMethod'
return ClassWithStaticMethod.staticMethod.name;
}
}
console.log('2: ' + ClassWithStaticMethod.staticMethod()); // output: '2: staticMethod'
Code sample
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With