Saturday, April 12, 2014

AngularJs: Splat Logging - A Simple $log Factory

Logging and debugging can be a pain

Background

Sometimes we must log/debug javascript. Kind of frequently, in fact, must the javascript things be logged/debugged. I work a lot in Chrome, which has this super neat object logger that folds objects and properties and collapses arrays and stuff.

In writing complex javascript, I find that I have to annotate what functions are running and under which conditions certain things are being called, which leads to a lot of code like:

console.log('I am about to log myObject: ');
console.log(myObject);
console.log('the myArray thingy: ');
console.log(myArray);
//or with AngularJs $log-->
$log.log('I am about to log myObject: ');
$log.log(myObject);
$log.log('the myArray thingy: ');
$log.log(myArray)

Splat Logging

Wouldn't it be super cool to be able to flip logging off and on easily?
Wouldn't it be super cool to just *splat* logging?

I thought so, so I wrote the following:

//the factory in this module allows you to splat angular's $log provider
//<jwLog>.log('so', { now : 'you' }, 'can' + 'log like', ['a','maniac']);
angular.module('jwLogModule',['ng'])
    .factory('jwLog', ['$log', function ($log) {
        var noOpLogger = function () {
            var n = angular.noop;
            this.info = n;
            this.debug = n;
            this.error = n;
            this.log = n;
            this.warn = n;
        };

        var debugLogger = function () {
            function logIt() {
                var args = [].slice.call(arguments);
                for (var i = 0; i < args[1].length; i++) {
                    $log[args[0]](args[1][i]);
                }
            }

            this.info = function () {
                logIt('info', arguments);
            };
            this.debug = function () {
                logIt('debug', arguments);
            };
            this.error = function () {
                logIt('error', arguments);
            };
            this.log = function () {
                logIt('log', arguments);
            };
            this.warn = function () {
                logIt('warn', arguments);
            };
        };

        var logger = function () {
            var args = [].slice.call(arguments)[0] || { debug: true };
            return (args.debug) ? new debugLogger() : new noOpLogger();            
        };

        return logger;
    }])

Here's a plunk: (view your browser console)

And this is what my browser console looks like:

No comments:

Post a Comment