Search code examples
javascriptlogginglog4javascriptlog4js-node

Javascript logging setup for unit testing and running browser based web app


I am working on a client side only javascript web app. I am using log4javascript for logging application functionality while running on a local server and becuase I couldn't get log4javascript to work during unit testing (in either Jasmine+Karma or Mocha), I am using log4js for logging while running unit tests on Node using Mocha.

To log during normal webb app running I create the log4javascript logger from a html page (as I cant figure out any way to create a glogal logger from a javascript.js file) using:

<script src="{{ url_for('static', filename='js/log4javascript.js') }}" type="text/javascript"></script>
<script type="text/javascript">
    var logger = log4javascript.getDefaultLogger();
</script> 

Beacause I want to log to the console during unit testing I need to set-up log4js in the same javascript.js files that I am logging from during normal web app running from. ie:

var log4js = require('log4js');
log4js.configure({
    appenders: [
        {
            "type": "logLevelFilter",
            "level": "DEBUG",
            "appender":
            {
                "type": "console"
            }
        }
    ]
});
var logger = log4js.getLogger();

then from inside functions I can use:

logger.debug("functionName message");

and this will work when logging from log4javascript and log4js, but this is messy as I have require('log4js') statements (that seem to be ignored when running on a browser) in every javascript file and there are two meanings for logger. Is there a better way to use logging during development of browser based javascript?


Solution

  • I ended up using console.log in the application code and the winston logger for unit testing.

    A good example of how console.log can be overriden can be found here: http://seanmonstar.com/post/56448644049/consolelog-all-the-things