Last active
April 19, 2018 10:22
-
-
Save wottpal/feb7e31dc7a1c2b1bb194b5424b00c78 to your computer and use it in GitHub Desktop.
A convenience wrapper around the Console API which adds several functionalities.
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
/** | |
* A convenience wrapper around the Console API which adds: | |
* - Logging has to be globally enabled first (in a dev-environment) | |
* - Even when disabled logged messages are cached and can be displayed later | |
* - Prefix messages with a custom〈 Label 〉 | |
* | |
* TODO Maybe add verbose-flag to really be able to log everything if needed | |
**/ | |
const debug = (() => { | |
/* Variables */ | |
let shouldLog = false | |
let cachedLog = [] | |
/* Private Functions */ | |
/** | |
* This function outputs all cache-messages. | |
*/ | |
function outputCache() { | |
if (!cachedLog || cachedLog.length <= 0) return | |
console.group(`Cached Messages (${cachedLog.length})`) | |
cachedLog.forEach(item => { | |
debug.log(item.message, item.type, item.label) | |
}) | |
console.groupEnd() | |
} | |
/** | |
* This function determines if the given label can be a string prefix | |
*/ | |
function canPrefixLabel(message) { | |
return ['number', 'boolean', 'string', 'undefined'].includes(typeof message) | |
} | |
/* Global Functions */ | |
return { | |
/** | |
* Enables logging and displays all cached messages while disabled. | |
*/ | |
'enable' : (enabled = true) => { | |
shouldLog = enabled | |
outputCache() | |
cachedLog = [] | |
}, | |
/** | |
* The actual logging function which can have a label and another type. | |
* See the Console API for all available types: https://goo.gl/rNW81W | |
*/ | |
'log' : (message, type = 'log', label) => { | |
// Cache message if logging is disabled | |
if (!shouldLog) { | |
cachedLog.push({ message: message, type: type, label: label}) | |
return; | |
} | |
// Prefix or print label on new line | |
if (label && canPrefixLabel(message)) { | |
message = `%c〈 ${label} 〉%c ${message}` | |
console[type](message, "color:gray", "") | |
} else { | |
if (label) console.group(`%c〈 ${label} 〉${typeof message}`, "color:gray;font-weight:normal") | |
console[type](message) | |
if (label) console.groupEnd() | |
} | |
}, | |
/** | |
* Returns a logger which always has the given label. | |
*/ | |
'labeledLogger' : (label) => { | |
return (message, type) => { | |
log(message, type, label) | |
} | |
}, | |
} | |
})() | |
/** | |
* Global Shortcuts | |
*/ | |
const log = debug.log | |
const labeledLogger = debug.labeledLogger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment