You have multiple choices to choose from for a logger, thanks to NPM. However, you can also create your own logger with just a bit of code. Here’s an example on how you can create a dev logger in JavaScript. Meaning, this logger will console errors to the console windows only during non-production mode:
const logCssColors =
'background: #008cf4; color: #ffffff; font-size: 12px; padding: 2px 4px;'
const logCssErrorColors =
'background: #974855; color: #ffffff; font-size: 12px; padding: 2px 4px;'
const devLogger = () => {
const isProd = process.env.NODE_ENV == 'production'
return {
log: function log(str) {
if (isProd) return
console.log('%c%s', logCssColors, str)
},
logNewline: function logNewline(str) {
if (isProd) return
console.log('%c%s\n', logCssColors, str)
},
logAllEnv: function logAllEnv(str) {
console.log('%c%s', logCssColors, str)
},
logError: function logError(str) {
if (isProd) return
console.log('%c%s', logCssErrorColors, str)
},
logErrorAllEnv: function logErrorAllEnv(str) {
console.log('%c%s', logCssErrorColors, str)
},
logErrorNewline: function logErrorNewline(str) {
if (isProd) return
console.log('%c%s\n', logCssErrorColors, str)
},
}
}
devLogger().log('Some test message!')
devLogger().log('Some test error!')
Code language: JavaScript (javascript)
Output:
In the code above, I’ve created a closure function named devLogger() with multiple inner functions:
log(): Returns the log in blue background and white text
logNewline(): Always returns the log message in a new line
logAllEnv(): Returns a log even in production mode
logError(): Log an error with red background
logErrorAllEnv(): Log errors even in production mode
logErrorNewline(): Log errors in new line
You can even crate more inner functions, thereby extending more logger options.