Last active
August 29, 2015 13:57
-
-
Save jonjaques/9744487 to your computer and use it in GitHub Desktop.
Simple logging service (wraps $log) for Angular.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app = angular.module 'demo', [] | |
app.controller 'TestCtrl', ($scope, Logger)-> | |
Logger.log 'generic log...' # generic log... | |
log = Logger.makeLogger 'TestCtrl' | |
log.log 'prefixed log' # TestCtrl: prefixed log | |
$scope.doStuff = ()-> | |
log.debug 'Supports all $log methods' # TestCtrl: Supports all $log methods |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Logger | |
constructor: (@injector)-> | |
@baseLog = @makeLogger() | |
# copy over base logger methods to the root obj | |
_.each @_methods, (fn)=> @[fn] = @baseLog[fn] | |
makeLogger: (logName)-> | |
$log = @injector.get '$log' | |
# create curried versions of $log so we can | |
# prefill logger name. | |
@_methods = _.functions $log unless @_methods | |
if logName and typeof logName is 'string' | |
logName = "#{logName}:" | |
_log = {} | |
_.each @_methods, (fn)-> | |
curryFn = _.partial $log[fn], logName | |
_log[fn] = ()-> | |
args = _.toArray arguments | |
curryFn.apply $log, args | |
return _log | |
return $log | |
Logger.$inject = ['$injector'] | |
# Register with your app like so... | |
app.service 'Logger', Logger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This could probably be accomplished with decorators too, but IMO they don't solve the problem they're intended to - as they modify all instances of the decorated object, including those injected into 3rd party code.
I think a wrapper works because the
$log
api is pretty stable, and this allows us more control in the future.