Created
May 5, 2015 17:41
-
-
Save vslinko/a4bdddc1ad02f34a29c7 to your computer and use it in GitHub Desktop.
my colourful logger
This file contains 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
import R from 'ramda'; | |
const levels = { | |
debug: 0, | |
log: 1, | |
info: 2, | |
warn: 3, | |
error: 4 | |
}; | |
const outputLevel = levels[process.env.LOG_LEVEL] || levels.debug; | |
const outputColor = (() => { | |
const chromeRegexp = /Chrome\/(\d+)/; | |
const matches = chromeRegexp.exec(navigator.userAgent); | |
return matches && Number(matches[1]) >= 24; | |
})(); | |
const levelNames = Object.keys(levels); | |
/* eslint-disable no-console */ | |
const debugHandler = (...args) => console.debug(...args); | |
const logHandler = (...args) => console.log(...args); | |
const infoHandler = (...args) => console.info(...args); | |
const warnHandler = (...args) => console.warn(...args); | |
const errorHandler = (...args) => console.error(...args); | |
/* eslint-enable no-console */ | |
const handlers = [ | |
debugHandler, // debug | |
logHandler, // log, | |
infoHandler, // info, | |
warnHandler, // warn | |
errorHandler // error | |
]; | |
const styles = [ | |
'background: white; color: gray; padding: 0 0 0 1em;', // debug | |
'background: lightgray; color: black; padding: 0 1em;', // log | |
'background: blue; color: white; padding: 0 1em;', // info | |
'background: white; color: red; padding: 0 0 0 1em;', // warn | |
'background: red; color: black; padding: 0 1em;' // error | |
]; | |
const log = R.curryN(3, function log(tag, level, message, data) { | |
if (!console.log || (process.env.NODE_ENV === 'production' && !/debug/.test(window.location.href)) || level < outputLevel) { | |
return; | |
} | |
const handler = handlers[level]; | |
let args; | |
if (outputColor) { | |
args = [ | |
`%c${tag}%c${levelNames[level]}%c${message}`, | |
'background: black; color: white; padding: 0 1em;', | |
styles[level], | |
'background: white; color: green; padding-left: 1em;' | |
]; | |
} else { | |
args = [ | |
`${tag}: ${levelNames[level]}: ${message}` | |
]; | |
} | |
if (data) { | |
args = args.concat([R.clone(data)]); | |
} | |
handler(...args); | |
}); | |
export { | |
levels, | |
log | |
}; |
This file contains 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
import {log, levels as logLevels} from './log'; | |
const logger = log('MyApplication'); | |
const debugFn = logger(levels.debug); | |
debugFn("Description"); | |
debugFn("Description", {some: 'metadata'}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment