Browse files

Add formatted logging methods. Closes #1

  • Loading branch information...
1 parent 8e8e6d0 commit cbff99356424d49c566e4830fca583e81c5f0968 @pquerna committed Jul 17, 2011
Showing with 46 additions and 2 deletions.
  1. +45 −2 lib/logmagic.js
  2. +1 −0 tests/t.js
View
47 lib/logmagic.js
@@ -98,6 +98,45 @@ function buildLogMethod(modulename, level, callback) {
}
}
+
+function applyFormatString(msg, extra) {
+ function replaceFunction(str, p1) {
+ if (extra.hasOwnProperty(p1)) {
+ return extra[p1];
+ }
+
+ return p1;
+ }
+ var regex = new RegExp(/\$\{(.*?)\}/g);
+ msg = msg.replace(regex, replaceFunction);
+ return msg;
+}
+
+function buildFormattedLogMethod(modulename, level, callback) {
+ if (level >= exports.TRACE1) {
+ return function (msg, extra) {
+ if (!extra) {
+ extra = {};
+ }
+ extra['full_message'] = new Error('Backtrace').stack;
+ extra = applyRewrites(modulename, level, msg, extra);
+ msg = applyFormatString(msg, extra);
+ callback(modulename, level, msg, extra)
+ }
+ }
+ else {
+ return function (msg, extra) {
+ if (!extra) {
+ extra = {};
+ }
+ extra = applyRewrites(modulename, level, msg, extra);
+ msg = applyFormatString(msg, extra);
+ callback(modulename, level, msg, extra)
+ }
+ }
+}
+
+
function nullLogger() {
/* Intentionally blank. */
}
@@ -107,18 +146,22 @@ function applyRoute(route, logger, modulename) {
for(var i=0; i<log_levels.length; i++) {
var level = log_levels[i];
var v = exports[level];
+ var llstr = level.toLowerCase();
if (v <= route.loglevel) {
- logger[level.toLowerCase()] = buildLogMethod(modulename, v, route.callback);
+ logger[llstr] = buildLogMethod(modulename, v, route.callback);
+ logger[llstr + 'f'] = buildFormattedLogMethod(modulename, v, route.callback);
}
else {
- logger[level.toLowerCase()] = nullLogger;
+ logger[llstr] = nullLogger;
+ logger[llstr + 'f'] = nullLogger;
}
}
for (var key in log_aliases) {
if (log_aliases.hasOwnProperty(key)) {
logger[key.toLowerCase()] = logger[log_aliases[key].toLowerCase()];
+ logger[key.toLowerCase() + 'f'] = logger[log_aliases[key].toLowerCase() + 'f'];
}
}
}
View
1 tests/t.js
@@ -3,6 +3,7 @@ var log = logmagic.local('mylib.foo.bar');
//console.log(log);
log.info("Hello!");
log.error("more stuff", {SOME_VAR: "myvalue"});
+log.errorf("more stuff: ${SOME_VAR}", {SOME_VAR: "myvalue"});
log.trace("testing trace v0");
logmagic.route("__root__", logmagic.TRACE1, "console");

0 comments on commit cbff993

Please sign in to comment.