Search code examples
angularjsangularjs-logangularjs-decorator

Incorrect logging message after override $log


I'm trying to decorate the angular's $log factory to put the timestamp of the message in the log.

It works pretty well until now, except for this behavior:

When I log with default configuration of angular, I receive:

message for Object {name: "bryan", message: "was here"} third argument

Plunker

After creating the decorator, the logs became this:

["message for", Object, "third argument"]

Plunker - The code is here

So, the Object was not expanded to the console, and I need to click at the message to see the full object.

Does anyone know what I'm missing? Or know a better way to do this and put the timestamp in the beginning of the message?


Solution

  • You need to expand the argument array into a list of arguments for warn(). You can achieve it with apply(). It is just a JavaScript trick.

    warn: function () {
        //create a new args. You can't modify arguments since it is controlled by AngularJS
        var args = [new Date()];
        angular.forEach(arguments, function (i) {
            args.push(i);
        })
        $delegate.warn.apply(null, args);
    }
    

    $delegate.warn.apply(null, args); evaluates as $delegate.warn(args[0], args[1], ...);.