Skip to content

Instantly share code, notes, and snippets.

@dylants
Created October 28, 2014 20:03
Show Gist options
  • Select an option

  • Save dylants/80ed06ffd8f5561f3dc5 to your computer and use it in GitHub Desktop.

Select an option

Save dylants/80ed06ffd8f5561f3dc5 to your computer and use it in GitHub Desktop.

Revisions

  1. dylants created this gist Oct 28, 2014.
    59 changes: 59 additions & 0 deletions logger.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    "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;