Skip to content

Instantly share code, notes, and snippets.

@rcmachado
Created February 5, 2013 18:08
Show Gist options
  • Select an option

  • Save rcmachado/4716386 to your computer and use it in GitHub Desktop.

Select an option

Save rcmachado/4716386 to your computer and use it in GitHub Desktop.

Revisions

  1. rcmachado created this gist Feb 5, 2013.
    54 changes: 54 additions & 0 deletions logger.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,54 @@
    /**
    * Logger class to print messages according to specified level.
    *
    * Usage:
    * var log = new Logger(Logger.INFO);
    * log.info("Show message");
    */

    function Logger(level) {
    this.level = level || Logger.DEBUG;
    }

    (function () {
    fn = Logger.prototype;

    /* Log levels */
    fn.DEBUG = 10;
    fn.INFO = 20;
    fn.WARNING = 30;
    fn.ERROR = 40;

    fn.LEVEL_NAMES = {};
    fn.LEVEL_NAMES[fn.DEBUG] = 'DEBUG';
    fn.LEVEL_NAMES[fn.INFO] = 'INFO';
    fn.LEVEL_NAMES[fn.WARNING] = 'WARNING';
    fn.LEVEL_NAMES[fn.ERROR] = 'ERROR';

    fn.log = function(level, msg) {
    if (level > this.level) {
    return;
    }

    var levelName = fn.LEVEL_NAMES[level],
    dateFull = ISODate().tojson(),
    dateString = dateFull.replace('ISODate("', '').replace('")', '');
    print(levelName + " " + dateString + " " + msg);
    };

    fn.debug = function(msg) {
    this.log(fn.DEBUG, msg);
    };

    fn.info = function(msg) {
    this.log(fn.INFO, msg);
    };

    fn.warning = fn.warn = function(msg) {
    this.log(fn.WARNING, msg);
    };

    fn.error = function(msg) {
    this.log(fn.ERROR, msg);
    };
    }());
    7 changes: 7 additions & 0 deletions usage.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    // Usage example for Logger javascript class
    // Don't forget to include the logger.js file

    var log = new Logger(Logger.INFO);
    log.info("This message will be printed on stdout");
    log.error("And so this one");
    log.debug("But this don't! (As Logger.INFO was specified on object creation.)");