Skip to content

Instantly share code, notes, and snippets.

@jonjaques
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonjaques/9744487 to your computer and use it in GitHub Desktop.
Save jonjaques/9744487 to your computer and use it in GitHub Desktop.
Simple logging service (wraps $log) for Angular.js
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
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
@jonjaques
Copy link
Author

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.

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