I want to use Azure Functions' context logging methods in my own class depending on the first word: if str starts with error then use context.error(str), otherwise use context.log(str).
I think I have to bind the function but cannot make it work. Full code here: https://runjs.co/s/vyCXfFJ$8
I was thinking of a one-liner but the following gives me the error message Exception: Cannot read private member from an object whose class did not declare it:
class Foo {
context;
constructor(context) {
this.context = context;
}
log(...args) {
return (args.length > 0 && typeof args[0] == "string" && args[0].toLowerCase().startsWith('error') ? this.context.error : this.context.log)(...args);
}
}
It works using if-else so I have a workaround but I wanted to understand the underlying problem. Who understands and can help?
if (args.length > 0 && typeof args[0] == "string" && args[0].toLowerCase().startsWith('error')) {
this.context.error(...args);
} else {
this.context.log(...args);
}
I tried to use .bind() but I'm getting the same error:
return (args.length > 0 && typeof args[0] == "string" && args[0].toLowerCase().startsWith('error') ? this.context.error : this.context.log).bind(this.context)(...args);
I tried using your code in my environment and got expected results:
Console Output if the context starts with
Error:Console Output if the context starts anything else other than
Error:Case 1:
Code Snippet:
Output:
Case 2:
Code Snippet:
Output: