Created
April 13, 2016 17:45
-
-
Save hattmarris/ae6aabc8511a1337afebfa630975b240 to your computer and use it in GitHub Desktop.
Logger Module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Logger(state) { | |
var on = setInitial(state), | |
levels = { | |
error: 0, | |
log: 1, | |
trace: 2 | |
}; | |
// Define on property getter and setter | |
Object.defineProperty(this, 'on', { | |
configurable: true, | |
enumerable: true, | |
get: function() { | |
console.log('get!'); | |
return on; | |
}, | |
set: function(value) { | |
console.log('set!'); | |
switch(value) { | |
case false: | |
this.turnOff(); | |
break; | |
case true: | |
this.turnOn(); | |
break; | |
} | |
}.bind(this) | |
}); | |
// Private methods | |
function setInitial(state) { | |
// Default is false (off) | |
var def = false; | |
// Validate state input is true or false | |
if(typeof state !== 'boolean') { | |
try { | |
throw new LoggerError('Initial state value representing on or off for the Logger must be boolean'); | |
} catch(e) { | |
console.log(e.name + ': ' + e.message); | |
return def; // return default | |
} | |
} else { | |
return state; | |
} | |
} | |
// For handling module exceptions, prototypally inherits from the Error constructor | |
function LoggerError(message) { | |
this.name = 'LoggerError'; | |
this.message = message || 'Error in the Logger module'; // message or default | |
this.stack = (new Error()).stack; | |
} | |
LoggerError.prototype = Object.create(Error.prototype); | |
LoggerError.prototype.constructor = LoggerError; | |
// Privileged methods | |
this.turnOff = function() { | |
on = false; | |
} | |
this.turnOn = function() { | |
on = true; | |
} | |
// Loop and set public methods for each level | |
Object.keys(levels).forEach( | |
function(level) { | |
Logger.prototype[level] = function(content) { | |
if(on) { | |
var stacktrace = new Error().stack; | |
content += stacktrace; | |
console[level].call(console, content); // Wraps around environment console object and calls those methods | |
} else { | |
return; | |
} | |
} | |
} | |
); | |
} | |
Logger.prototype.constructor = Logger; | |
module.exports = Logger; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment