DEV Community

Discussion on: What JS Logging library / tool do you use?

Collapse
 
download profile image
Stijn de Witt

The problem with using console directly is that there are browsers out there (probably only real old ones though) that simply crash your code right away because console is undefined when the developer tool is not opened. Also some interpreters, such as Nashorn which comes with Java, simply do not have a console defined.

If you want to avert that risk and still only use the console for logging, you should write code similar to this:

var log = (typeof console != 'undefined') && console 
// Testing with typeof is better than window.console 
// since it works everywhere, inclucing Node JS / Nashorn
log && log.info('If the console is not there, this code will not crash')

However, this means testing log before each call to log.info... You could maybe do this to prevent that test:

var log = typeof console != 'undefined' ? console : {info:function(){}}
log.info('This code calls a dummy function if console is not there')

However, you would also have to make dummies for warn(), error() etc... In the end you would be building a shim... Which is exactly how ulog started. I understand your desire to keep logging simple and not use any external libs for it... But really the state of JS today is that 'simple' logging either is broken (crashes on some systems), is not actually 'simple' (see code examples above), or does use a library. I built ulog from the desire to make it as close to using no lib at all, while actually solving those problems. If you never use any logging lib, ulog was built with you in mind! Please try it and let me know.