In my code, I am logging multiple messages in a static method and I want to use the method name as context. However, I do not want to create a separate variable called `context` and assign the function/method name to it.
I would like to be able to access the context by directly getting the method name, not only in a class static method but also in every other function.
Below is my attempt:
class CloudFunction {
public static parse() {
console.log(this.name); // CloudFunction
console.log(CloudFunction.parse.name); // unable to retrieve anything here
// Rather than declaring a `context` variable and assigning the method name to it.
const context = 'parse';
logger.debug('a log', { context, arguments: 'pubsubMessage' });
//... many logs use this context
// hoping for a better solution like:
// const self = this;
// logger.error(new Error('bad'), {context: self.name })
}
}
CloudFunction.parse();
Unfortunately, none of these methods seem to work. Is there a way to use reflection to achieve this? I am uncertain if reflection can accomplish this task.
update
Here are my findings:
☁ DL-Toolkits [master] npx ts-node /Users/ldu020/workspace/github.com/mrdulin/ts-codelab/src/class/get-static-method-name/index.ts
CloudFunction