Permalink
Browse files

Added simple formatter

  • Loading branch information...
showstopper committed Nov 6, 2011
1 parent 70ba965 commit 9776129dec5fab6506780809bd9f88a277b966a3
Showing with 54 additions and 4 deletions.
  1. +36 −0 lib/Formatter.coffee
  2. +11 −1 lib/Handler.coffee
  3. +3 −1 lib/Logger.coffee
  4. +2 −0 lib/cyanide.coffee
  5. +2 −2 test.coffee
View
@@ -0,0 +1,36 @@
+formatTemplate = (str, toReplace) ->
+ ###
+ Poor man's template engine. Poor man can't engineer, poor man needs food.
+ Example: "[{{dateTime}}] [{{level}}] [{{emitter}}] {{msg}}"
+
+ str: template string
+ toReplace: keys : 'result' value
+ ###
+
+ for key in Object.keys(toReplace)
+ str = str.replace("{{#{key}}}", toReplace[key])
+ str
+
+class Formatter
+
+ format: (handler, logger, level, emitter, msg) ->
+ msg
+
+class NiceFormatter
+
+ constructor: (@template="[{{dateTime}}] [{{level}}] [{{emitter}}] {{msg}}") ->
+
+
+ format: (handler, logger, level, emitter, msg) ->
+
+ map_ = {
+ "level" : level.toString(),
+ "msg" : msg,
+ "emitter": emitter.path,
+ "dateTime" : new Date().toString()
+ }
+
+ formatTemplate @template, map_
+
+exports.Formatter = Formatter
+exports.NiceFormatter = NiceFormatter
View
@@ -1,11 +1,21 @@
+Formatter = require "./Formatter"
+
class Handler
handle: (logger, level, emitter, msg) ->
formatted = msg
@send(logger, level, emitter, msg, formatted) # why msg+formatted?
-class StreamHandler extends Handler
+class ExtendedHandler extends Handler
+
+ constructor: (@formatter=new Formatter.Formatter) ->
+
+ handle: (logger, level, emitter, msg) ->
+ formatted = @formatter.format this, logger, level, emitter, msg
+ @send(logger, level, emitter, msg, formatted) # why msg+formatted?
+
+class StreamHandler extends ExtendedHandler
send: (logger, level, emitter, msg, formatted) ->
@stream.write formatted
View
@@ -1,8 +1,10 @@
Level = require ("./Level")
+
class Logger
- constructor: ->
+ constructor: (@path="") ->
@handlers = []
+ formatter = null
log: (level, emitter, msg) ->
handler.handle(this, level, emitter, msg) for handler in @handlers
View
@@ -2,6 +2,7 @@ fs = require "fs"
Handler = require "./Handler"
Logger = require "./Logger"
+Formatter = require "./Formatter"
class Log
@@ -20,3 +21,4 @@ class Log
exports.Log = Log
exports.StdoutHandler = Handler.StdoutHandler
exports.StderrHandler = Handler.StderrHandler
+exports.NiceFormatter = Formatter.NiceFormatter
View
@@ -1,7 +1,7 @@
cyanide = require "./lib/cyanide"
-consoleHandler = new cyanide.StdoutHandler
+consoleHandler = new cyanide.StdoutHandler(new cyanide.NiceFormatter)
cyanide.Log.attachHandler consoleHandler
-myLogger = cyanide.Log.getLogger ""
+myLogger = cyanide.Log.getLogger "cyanide"
myLogger.debug "Debug"

0 comments on commit 9776129

Please sign in to comment.