如何使用时间戳和类名增强 Angular 的$log?



如何使 Angular 在其日志中添加时间戳和类名?

像这样:

$log.info('this log entry came from FooBar');

"9:37:18 pm, FooBar:此日志条目来自 FooBar"

我在网上找到的例子要么不清楚,要么结合了许多其他东西(如requirejs)。我确实发现了一些进入 Angular 装饰器的示例,但我想知道是否有更简单的方法。

> 16-05-2015:这段代码被变成了一个名为angular-logger的GitHub项目。下面显示的代码相当过时。


不必使用装饰器。你可以用一些基本的javascript来欺骗Angular的$log:

app.run(['$log', function($log) {
    $log.getInstance = function(context) {
        return {
            log   : enhanceLogging($log.log, context),
            info  : enhanceLogging($log.info, context),
            warn  : enhanceLogging($log.warn, context),
            debug : enhanceLogging($log.debug, context),
            error : enhanceLogging($log.error, context)
        };
    };
    function enhanceLogging(loggingFunc, context) {
        return function() {
            var modifiedArguments = [].slice.call(arguments);
            modifiedArguments[0] = [moment().format("dddd h:mm:ss a") + '::[' + context + ']> '] + modifiedArguments[0];
            loggingFunc.apply(null, modifiedArguments);
        };
    }
}]);

用法:

var logger = $log.getInstance('Awesome');
logger.info("This is awesome!");

输出:

星期一 9:37:18 pm::[太棒了]>这太棒了!

我使用Moment.js进行时间戳格式设置。此示例使用 Angular 的模块运行块支持在其他任何内容开始运行之前配置应用程序。

对于更优雅和可配置的解决方案,下面是相同的日志增强器,但作为可配置的提供程序:

angular.module('app').provider('logEnhancer', function() {
    this.loggingPattern = '%s - %s: ';
    this.$get = function() {
        var loggingPattern = this.loggingPattern;
        return {
            enhanceAngularLog : function($log) {
                $log.getInstance = function(context) {
                    return {
                        log : enhanceLogging($log.log, context, loggingPattern),
                        info    : enhanceLogging($log.info, context, loggingPattern),
                        warn    : enhanceLogging($log.warn, context, loggingPattern),
                        debug   : enhanceLogging($log.debug, context, loggingPattern),
                        error   : enhanceLogging($log.error, context, loggingPattern)
                    };
                };
                function enhanceLogging(loggingFunc, context, loggingPattern) {
                    return function() {
                        var modifiedArguments = [].slice.call(arguments);
                        modifiedArguments[0] = [ sprintf(loggingPattern, moment().format("dddd h:mm:ss a"), context) ] + modifiedArguments[0];
                        loggingFunc.apply(null, modifiedArguments);
                    };
                }
            }
        };
    };
});

要使用和配置它:

var app = angular.module('app', []);
app.config(['logEnhancerProvider', function(logEnhancerProvider) {
    logEnhancerProvider.loggingPattern = '%s::[%s]> ';
}]);
app.run(['$log', 'logEnhancer', function($log, logEnhancer) {
    logEnhancer.enhanceAngularLog($log);
}]);

最新更新