AngularJS : why you should use the $log service instead of console.log()

AngularJS : why you should use the  $log service instead of console.log()

AngularJS : why you should use the $log service instead of console.log()

 

What is $log

$log is a simple service for logging purposes. Default implementation safely writes the message into the browser’s console (if present). The main purpose of this service is to simplify debugging and troubleshooting.

 

Why to use $log

$log first checks if console.log is available. In IE 8, for instance, the console object is created when the dev tools are opened, meaning when the dev tools is never opened – there will never be a console object available.

function consoleLog(type) {
    var console = $window.console || {},
        logFn = console[type] || console.log || noop;

    return function() {
        var args = [];
        forEach(arguments, function(arg) {
            args.push(formatError(arg));
        });
        // Support: IE 9 only
        // console methods don't inherit from Function.prototype in IE 9 so we can't
        // call `logFn.apply(console, args)` directly.
        return Function.prototype.apply.call(logFn, console, args);
    };
}

From log.js source code – https://github.com/angular/angular.js/blob/master/src/ng/log.js#L134

 
Besides this the $log service makes it possible to easily to decorate or mock itself
 

Also the $log service support a JavaScript Error instance. It will format the Error instance.

function formatError(arg) {
    if (arg instanceof Error) {
        if (arg.stack & amp; & amp; formatStackTrace) {
            arg = (arg.message & amp; & amp; arg.stack.indexOf(arg.message) === -1) ?
                'Error: ' + arg.message + '\n' + arg.stack :
                arg.stack;
        } else if (arg.sourceURL) {
            arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
        }
    }
    return arg;
}

From log.js source code – https://github.com/angular/angular.js/blob/master/src/ng/log.js#L134

It also allows you to decorate and mock $log for extending and testing purposes, if you are so inclined. You could for example decorate it to log to an array for IE 8 support.

 

Downside of $log

Using $log has a downside as well… If you use the console.log approach you can see the file and the line number of where the actual logging is invoked from. With $log it will always show angular.js as the source of the log in your console.

 

Easily enabling / disabling $log on switching to production

Easily enable or disable the logger service on the module config block.

app.config(function($logProvider) {
  $logProvider.debugEnabled(true); // disable logger
  $logProvider.debugEnabled(false); // enable logger
});

or using a decorater on the $log service in combination with a module constant.

angular
  .module('app', [])
  .controller('LogController', LogController)
  .constant('debugEnabled', false) // change to TRUE | FALSE to enable or disable $log

.config(function($logProvider, $provide) {
  // decorate $log
  $provide.decorator('$log', function($delegate, debugEnabled) {
    // check delegate method
    $delegate.debug = debugEnabled ? $delegate.debug : function() { alert('$log disabled'); };
    $delegate.info = debugEnabled ? $delegate.info : function() { alert('$log disabled'); };
    $delegate.warn = debugEnabled ? $delegate.warn : function() { alert('$log disabled'); };
    $delegate.error = debugEnabled ? $delegate.error : function() { alert('$log disabled'); };
    $delegate.log = debugEnabled ? $delegate.log : function() { alert('$log disabled'); };
    // return delegate
    return $delegate;
  });
});

See JSFiddle

 

Sample code


About the Author

Daan is a Creative-Geek who loves learning and sharing new techniques! Follow him on Twitter to keep up to date with the Creative-Geeks blog and other subjects. Contact him on e-mail : info[at]creative-geeks.com.