Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use $logProvider for logging in config block of the module?

I'd like to output log messages to console when debugging. Works fine in controllers but can't get it to work in a module config block, e.g.

angular.module('MyApp', [])
  .run(function($state){
    // run stuff here
  });
  .config(function($logProvider){
    $log.debug('Config debug message');
  });

I get an error:

error TypeError: Cannot read property 'debug' of undefined

Is it possible to use the logProvider in the config block of a module?

like image 999
onblur Avatar asked Sep 22 '14 23:09

onblur


1 Answers

$logProvider accessed during the config phase is used to configure the log service, or you can inject $provide to change/leverage the behavior of logservice using decorators. The log service itself has not been instantiated yet in your module MyApp. You could instead get a logger instance from core ng and use it for debugging.

You could do:-

 .config(function(){
     var $log =  angular.injector(['ng']).get('$log')
     $log.debug('Config debug message');
  });

$logProvider.$get will give you the constructor for logservice, you could yourself create an instance of it by calling $injector.instantiate($logProvider.$get) but the problem is that it has a dependency on window service which has not bee instantiated yet, so ultimately your logger instantiation will fail.

Another hacky way would be force angular to instantate logger by adding a decorator in the config block which you can set up as the first config block before any config logging is required, after that you can execute the ctor from $logProvider getter and get the instance of a logger.

.config(function($provide){
   //Just a dummy decorator
   $provide.decorator('$log', function($delegate){
      return $delegate;
  });

}).config(function($logProvider){
   //get logger instance
   var log = $logProvider.$get();
   log.debug("Got it");
});

Plnkr

like image 191
PSL Avatar answered Sep 28 '22 07:09

PSL