gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:48:34 28 4
gpt4 key购买 nike

我怎样才能让 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::[太棒了]>这太棒了!

我用了Moment.js用于时间戳格式。这个例子使用 Angular 的 module run block支持在其他任何东西开始运行之前配置应用程序。

对于更优雅和可配置的解决方案,这里有相同的日志增强器,但作为可配置的提供者:

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);
}]);

关于javascript - 如何使用时间戳和类名增强 Angular 的 $log?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20751516/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com