loading...

Logging in AngularJS 1.x

codeprototype profile image Kevin Le ・2 min read

console.log can be easily oversighted and left in places before the code goes to production. Of course, in production, the console should be as clean as possible. But occasionally, it would be nice to temporary turn them on for a quick troubleshooting.

AngularJS already has a service called $log but its problem is that it does not show the correct file and line number.

AngularJS $log

So here's a quick solution I came up with. Let's call this service loggingService. It contains a way that indicates whether logging is enabled or not. Because the service has to remember this even after users refresh the browsers, this cannot be a simple flag. Rather it has to be persisted to the local storage. Here's how the service implemented:

(function () {
  'use strict';
  angular.module('myapp').
    factory('loggingService', ['$window',
      function ($window) {
        const storage = $window.localStorage;
        const debug = {
          debug: $window.console.debug.bind($window.console, 'debug: %s'),
          log: $window.console.log.bind($window.console, 'log: %s'),          
          info: $window.console.info.bind($window.console, 'info: %s'),
          warn: $window.console.warn.bind($window.console, 'warn: %s'),
          error: $window.console.error.bind($window.console, 'error: %s'),
        };        
        const noOp = {
          debug(){},
          log(){},
          info(){},          
          warn(){},
          error(){},          
        };
        return {
          setEnable(enabled) {            
            storage.setItem('enable_logging', enabled);
          },
          console() {
            return storage.getItem('enable_logging') === 'true' ? debug : noOp;
          },
          getEnable() {
            return storage.getItem('enable_logging') === 'true' ? true : false;
          },
        }
       }
      },
  ]);
})();

Then in other Angular services and controllers, I just have to inject this loggingService and wherever console.log is called, I just have to replace with loggingService.console().log or loggingService.console().info or loggingService.console().warn or other methods. It works just before with the correct file and line number. But even better than before, in the Developer Tools console, I can now also filter these messages.

Developer Tools filter

Discussion

pic
Editor guide