Skip to content

Instantly share code, notes, and snippets.

@Wizek
Last active October 11, 2015 20:58
Show Gist options
  • Save Wizek/3918660 to your computer and use it in GitHub Desktop.
Save Wizek/3918660 to your computer and use it in GitHub Desktop.
Superpowered logging for AngularJS
// Superpowered logging for AngularJS.
angular.module('logFactory', ['ng'])
.value('logFactory_whiteList', /.*/)
//.value('logFactory_whiteList', /!|.*Ctrl|run/)
.value('logFactory_piercingMethods', {warn:true, error:true})
.factory('logFactory', ['$log', 'logFactory_whiteList' , 'logFactory_piercingMethods', function ($log, whiteList, piercing) {
piercing = piercing || {}
whiteList = whiteList || /.*/
return function (prefix, parentLog) {
var log = parentLog || $log
var match = prefix.match(whiteList)
function e(fnName) {
if (!log[fnName]) {
fnName = 'log'
}
return (piercing[fnName] || match)
? log[fnName].bind(log, '[' + prefix + ']')
: angular.noop
}
return (
{ debug: e('debug')
, info: e('info')
, log: e('log')
, warn: e('warn')
, error: e('error')
}
)
}
}])
@Wizek
Copy link
Author

Wizek commented Oct 19, 2012

Example usage:

.run(function (logFactory) {                                                  
  var logLevel1 = logFactory('level 1')                                       
  var logLevel1_1 = logFactory('level 1_1', logLevel1)                        
  var logLevel1_2 = logFactory('level 1_2', logLevel1)                        
  var logLevel1_1_1 = logFactory('level 1_1_1', logLevel1_1)                  
  logLevel1.log('one')                                                        
  logLevel1_1.log('two')                                                      
  logLevel1_2.log('three')                                                    
  logLevel1_1_1.log('four')                                                   
})                                                                            

Which outputs:

[level 1] one
[level 1] [level 1_1] two
[level 1] [level 1_2] three
[level 1] [level 1_1] [level 1_1_1] four 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment