I need something more sophisticated than console.log()
I put a lot of logging in, and I need to be able to quickly and easily control what is getting logged.
The main thing I need is to be able to easily turn logging on and off based on context and level. For example...declare a logger for this class or function, and turn it on and off for specific contexts and levels.
My other main headache is determining the context. I would love to be able to create a logger for a class (the category would be the class name). Then when logging inside methods, it would be ideal to have the logger append the method name. It turns out that having something automatically determine its caller is a total nightmare in Javascript. It's either deprecated, a strict mode violation, or an expensive and huge pain in the rumpus. (basically, you have to do some permutation of...throw an error...get the stack trace...parse it...and get the caller).
So, while I can do something like this: class MyClass {
constructor() {
const logger = new Logger(MyClass.name);
}
...
myMethod() {
logger.info("myMethod", "some log message");
// or even nicer
logger.startGroup("myMethod");
logger.info("some log message");
logger.endGroup();
}
}
The log message in myMethod above would ideally look like this:
(i) MyClass.myMethod: some log message
I would rather the logger just "know" that it is in MyClass.myMethod and print that out than for me to have to do tricks to find the context.
Basically, I need something similar to log4js, but this isn't a package that you can import. You can "request" it, but whenever I've requested a package, I can't find any evidence that it was evaluated/accepted/rejected.
Does Wix/Velo have anything built in for more bad-ass logging? Is there a package that Wix already supports that I could install? Or do I need to roll my own?
Thanks
Tracey
Hey @polkaset,
I know some logging libraries exist on npm and you should be able to use them on Wix. I personally build my own logging system because I only needed some basic requirements. Something like
export const INFO_LEVEL = 1 export const DEBUG_LEVEL = 0 export Class Logger { constructor(level, module = "", method="") { this.level = level } info(method, message) { if(this.level >= INFO_LEVEL) console.info("["+this.module+"]","["+method+"]", message) } debug(method, message) { if(this.level >= DEBUG_LEVEL)console.log("["+this.module+"]","["+method+"]", message) } }
You can then use dependency injection to create your Object
export default class MyClass { constructor(logger) { this.logger = logger } ... myMethod() { logger.info("myMethod", "some log message"); }
Then you use it like this
//Page code import {Logger, DEBUG_LEVEL) from 'public/utils/Logger.js' import MyClass from 'public/class/MyClass.js' const logger = new Logger(DEBUG_LEVEL)// Change the level to filter logs const my1 = new MyClass(logger);
Does it seem like a solution for you?