Skip to content

Instantly share code, notes, and snippets.

@rcmachado
Created February 5, 2013 18:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcmachado/4716386 to your computer and use it in GitHub Desktop.
Save rcmachado/4716386 to your computer and use it in GitHub Desktop.
Javascript "class" (Logger) to use in MongoDB scripts. This class prints the messages (respecting log level specified on constructor).
/**
* 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);
};
}());
// 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.)");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment