Skip to content

Instantly share code, notes, and snippets.

@dylants
Created October 28, 2014 20:03
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 dylants/80ed06ffd8f5561f3dc5 to your computer and use it in GitHub Desktop.
Save dylants/80ed06ffd8f5561f3dc5 to your computer and use it in GitHub Desktop.
Node application logger using the debug module. This automatically determines the namespace for the calling file/class/library by generating a stack trace on creation. Provides 2 loggers, one for log and one for error.
"use strict";
var debug = require("debug");
// enable the "myApp" namespace by default
debug.enable("myApp*");
// returns the calling filename, but prepended with "myApp:"
function _getDecorator() {
// the code below screws up test output when a test fails,
// so in the test environment, set this to return a constant
// string rather than determining the decorator via stack trace.
if (process.env.NODE_ENV === "test") {
return "myApp:test_environment";
}
try {
var err = new Error();
var callerfile;
var currentfile;
Error.prepareStackTrace = function(err, stack) {
return stack;
};
currentfile = err.stack.shift().getFileName();
while (err.stack.length) {
callerfile = err.stack.shift().getFileName();
if (currentfile !== callerfile) {
// trim the file to the file name itself (minus the .js)
callerfile = callerfile.slice(callerfile.lastIndexOf("/") + 1, callerfile.indexOf(".js"));
// prepend the project name
return "myApp:" + callerfile;
}
}
} catch (err) {}
return undefined;
}
function logger() {
var decorator, log, error;
// get the filename which is used to decorate the debug module
decorator = _getDecorator();
// setup two debug'ers, one for console.log and one for console.error
log = debug(decorator);
error = debug(decorator);
error.log = console.error.bind(console);
// return the two under the log and error functions
return {
log: log,
error: error
};
}
module.exports = logger;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment