05-16-2015: the code mentioned above has been transformed into a GitHub repository known as angular-logger. The displayed code is now considered outdated.
If you wish, you can bypass decorators and manipulate Angular's $log using simple JavaScript methods:
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);
};
}
}]);
Usage:
var logger = $log.getInstance('Awesome');
logger.info("This is awesome!");
Output:
Monday 9:37:18 pm::[Awesome]> This is awesome!
Moment.js was utilized for timestamp formatting in this example. The Angular application's configuration is set up using the module run block.
To achieve a more refined and customizable approach, here is the same log enhancer implemented as a configurable provider:
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);
};
}
}
};
};
});
To utilize and customize it:
var app = angular.module('app', []);
app.config(['logEnhancerProvider', function(logEnhancerProvider) {
logEnhancerProvider.loggingPattern = '%s::[%s]> ';
}]);
app.run(['$log', 'logEnhancer', function($log, logEnhancer) {
logEnhancer.enhanceAngularLog($log);
}]);