Skip to content

Instantly share code, notes, and snippets.

@lethak
Created February 1, 2018 14:32
Show Gist options
  • Save lethak/f32323566d228210a0d39a92dca4396f to your computer and use it in GitHub Desktop.
Save lethak/f32323566d228210a0d39a92dca4396f to your computer and use it in GitHub Desktop.
const enabled = (typeof process.env.DEBUG_ENABLED === 'undefined') ? false : process.env.DEBUG_ENABLED
const functionList = Object.keys(global.console)
export const factory = function (prefix, consoleObject) {
if (typeof prefix === 'undefined') {
prefix = null
}
if (typeof consoleObject === 'undefined') {
consoleObject = global.console
}
if (enabled && prefix === null) {
return consoleObject
}
let consoleObj = {
prefix,
...consoleObject
}
if (typeof consoleObj.prefix !== 'undefined') {
functionList.forEach((fName, i) => {
let origFunction = consoleObj[fName]
consoleObj[fName] = function () {
let finalPrefix = consoleObj.prefix
if (typeof consoleObj.prefix === 'function') {
finalPrefix = consoleObj.prefix()
}
if (finalPrefix !== '' && finalPrefix !== null) {
arguments[0] = `[${finalPrefix}] ${arguments[0]}`
}
if (enabled || fName === 'error') {
return origFunction.apply(null, arguments)
}
}
})
}
return consoleObj
}
/*
Usage:
this.console = require('../console').factory(() => {
return 'My Prefix '
})
this.console.log('Foobar', [1,2,3]) // output: '[My Prefix] Foobar' >(3) [1, 2, 3]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment