Kevin Hakanson
Kevin Hakanson

Reputation: 42210

Include AngularJS module and controller names in $log output?

I am investigating logging options and conventions in AngularJS. I would like my $log output to contain both the module and controller names (similar to loggers in Log4j). With the code below, I was able to inject the controller name into the $scope

var app = angular.module("demo", []);

app.config(['$provide', function ($provide) {
    $provide.decorator('$controller', [
        '$delegate',
        function ($delegate) {
            return function(constructor, locals) {
                if (angular.isString(constructor)) {
                    locals.$scope.controllerName =  constructor;
                }
                return $delegate(constructor, locals);
            }
        }]);
}]);

app.controller('SampleCtrl', ['$scope', '$log', function ($scope, $log) {
    $log.log("[" + app.name + "." + $scope.controllerName +"] got here");
}]);

I would like to solve this a better way. Specifically:

  1. Is there a better way to access the controller name that adding it to the $scope?
  2. Is there a way to get the module name instead of fetching "demo" from the .name property of the module app ?
  3. Similar to Enhancing $log in AngularJs the simple way, what is the best way to inject formatting like prepending "[module.controller]" into the $log.log() calls?

Upvotes: 4

Views: 456

Answers (0)

Related Questions