禁用登录AngularJS

Disable Logging on AngularJS

本文关键字:AngularJS 登录      更新时间:2023-09-26

我在代码中使用angularJS服务进行日志记录($log.error()、$log.debug()、$log.info()等),它运行良好。

现在,我正在尝试禁用所有日志。我已经试过了:

var app = angular.module('app', []);
app.config(
    ['$logProvider',
    function ($logProvider) {
        $logProvider.debugEnabled(false);
    }]
);

但这并没有什么作用,日志继续显示。。。

禁用我放在代码中的所有angularJS日志的最佳方法是什么?

编辑:

我这样称呼日志:

(function () {
    app.controller('MyController', ['$log',
            function($log) {
                 this.testFunction = function() {
                    $log.debug("debug");
                    $log.info("info");
                    $log.error("error");
                };
            }])
})();

您可以"覆盖"日志记录方法,如下所示(此处为全文):

angular.module('app', [])
.config(['$provide', function ($provide) {
    $provide.decorator('$log', ['$delegate', function ($delegate) {
        // Keep track of the original debug method, we'll need it later.
        var origDebug = $delegate.debug;
        /*
         * Intercept the call to $log.debug() so we can add on 
         * our enhancement. We're going to add on a date and 
         * time stamp to the message that will be logged.
         */
        $delegate.debug = function () {
            var args = [].slice.call(arguments);
            args[0] = [new Date().toString(), ': ', args[0]].join('');
            // Send on our enhanced message to the original debug method.
            origDebug.apply(null, args)
        };
        return $delegate;
    }]);

你还应该阅读http://blog.projectnibble.org/2013/12/23/enhance-logging-in-angularjs-the-simple-way/查看如何创建完整的日志记录提供程序,您可以在该提供程序中配置

这是我的两分钱:

var IN_DEVELOPMENT = true;
$provide.decorator('$log', ['$delegate', function ($delegate)
{
        var originals = {};
        var methods = ['info' , 'debug' , 'warn' , 'error'];
        angular.forEach(methods , function(method)
        {
            originals[method] = $delegate[method];
            $delegate[method] = function()
            {
                if (IN_DEVELOPMENT) {
                    var args = [].slice.call(arguments);
                    var timestamp = new Date().toString();
                    args[0] = [timestamp.substring(4 , 24), ': ', args[0]].join('');
                    originals[method].apply(null , args);
                }
            };
       });
       return $delegate;
}]);

只需设置布尔值即可。

debugEnabled函数应仅禁用$log.debug()消息。因此,如果您想像您所写的那样使用简单的config禁用日志记录,那么将所有调试调用重命名为$log.debug,而不是$log.log$log.error$log.info$log.whatever

你可以在这里看到一个例子http://jsfiddle.net/jccrosby/N2B6R/light/