Created
March 9, 2011 20:25
-
-
Save technoweenie/862930 to your computer and use it in GitHub Desktop.
Minimal node.js logger
This file contains 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
# logger = require('logger').create() | |
# logger.info("blah") | |
# => [2011-3-3T20:24:4.810 info (5021)] blah | |
# logger.debug("boom") | |
# => | |
# logger.level = Logger.levels.debug | |
# logger.debug(function() { return "booom" }) | |
# => [2011-3-3T20:24:4.810 error (5021)] booom | |
class Logger | |
constructor: (options) -> | |
@options = options or {} | |
@level = @options.level or Logger.levels.info | |
for level, num of Logger.levels | |
Logger.define @, level | |
add: (level, message, callback) -> | |
if @level > (Logger.levels[level] or 5) | |
return | |
if callback | |
message = callback() | |
else if typeof(message) == 'function' | |
message = message() | |
@write( | |
timestamp: new Date | |
severity: level | |
message: message | |
pid: process.pid | |
) | |
# Overwrite this to write to a file, a db, etc | |
write: (options) -> | |
console.log @build_message(options) | |
build_message: (options) -> | |
"[#{options.timestamp.getUTCFullYear()}" + | |
"-#{options.timestamp.getUTCMonth()+1}" + | |
"-#{options.timestamp.getUTCDay()}" + | |
"T#{options.timestamp.getUTCHours()}" + | |
":#{options.timestamp.getUTCMinutes()}" + | |
":#{options.timestamp.getUTCSeconds()}" + | |
".#{options.timestamp.getUTCMilliseconds()}" + | |
" #{options.severity} (#{process.pid})] " + | |
"#{options.message}" | |
Logger.define = (logger, level) -> | |
logger[level] = (message, callback) -> | |
@add level, message, callback | |
Logger.levels = | |
debug: 1 | |
info: 2 | |
warn: 3 | |
error: 4 | |
fatal: 5 | |
exports.create = (type, options) -> | |
new Logger(options) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment