Created
October 3, 2012 03:12
-
-
Save liamcurry/3824742 to your computer and use it in GitHub Desktop.
A small logging function to share between the client and server, inspired by winston
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
/* This needs some work, and is probably pretty broken at the moment. Will come back to this later. */ | |
define([ | |
'underscore' | |
], function ( | |
_ | |
) { | |
console.log(this); | |
var root = this; | |
var defaults = { | |
// Methods that should be passed to `console` | |
passMethods: [ | |
'assert', 'clear', 'count', 'dir', 'dirxml', 'exception', 'group', | |
'groupCollapsed', 'groupEnd', 'profile', 'profileEnd', 'table', 'time', | |
'timeEnd', 'trace' | |
], | |
shouldPassMethods: true, | |
logLevels: ['error', 'warn', 'info', 'debug', 'log'], | |
logLevel: 'log', | |
callback: null, | |
transports: [root.console] | |
}; | |
function Logger(options) { | |
options = _.extend(defaults, options || {}); | |
this.passMethods = options.passMethods; | |
this.shouldPassMethods = options.shouldPassMethods; | |
this.logLevels = options.logLevels; | |
this.logLevel = options.logLevel; | |
this.callback = options.callback; | |
this.transports = options.transports; | |
for (var i=this.passMethods.length, method; i--;) { | |
method = this.passMethods[i]; | |
this[method] = function () { | |
if (this.shouldPassMethods && this.logLevel && | |
console && console[method]) { | |
console[method].apply(console, arguments); | |
} | |
}; | |
} | |
for (var l=this.logLevels.length, level; l--;) { | |
level = this.logLevels[l]; | |
this[level] = function () { | |
this.writeLog.apply(level, arguments); | |
if (!this.isLevel(level)) return; | |
for (var t=this.transports.length, transport; t--;) { | |
transport = this.transports[t]; | |
transportFn = transport[level] || transport.log; | |
if (transportFn) transportFn(arguments); | |
} | |
}; | |
} | |
} | |
Logger.prototype.isLevel = function (level) { | |
if (_.isNaN(level)) level = _.indexOf(this.logLevels, level); | |
return this.logLevel > level; | |
}; | |
Logger.prototype.writeLog = function () { | |
this.log.push(arguments); | |
}; | |
return Logger; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment