Skip to content

Instantly share code, notes, and snippets.

@Paratron
Created May 21, 2019 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Paratron/00c4e170cd83eb15a0ad69b316041f88 to your computer and use it in GitHub Desktop.
Save Paratron/00c4e170cd83eb15a0ad69b316041f88 to your computer and use it in GitHub Desktop.
This tiny wrapper around chalk enables easy coloring of log messages.
/**
* Chalk powered color log
* =======================
* This module is a wrapper around the chalk package to provide
* simpler log message formatting.
* To switch a color inside your log message, simply use ´X where
* X is one of the color names in the chalkMap below.
*
* Example:
*
* console.log('Roses are ' + chalk.red('red') + ', violets are ' + chalk.blue('blue') + '.');
*
* vs:
*
* log('Roses are `rred`w, violets are `bblue`w.');
*
*/
const chalk = require('chalk');
const chalkMap = {
'r': 'red',
'g': 'green',
'y': 'yellow',
'b': 'blue',
'm': 'magenta',
'c': 'cyan',
'w': 'white',
'#': 'gray',
'.': 'black',
'R': 'bgRed',
'G': 'bgGreen',
'Y': 'bgYellow',
'B': 'bgBlue',
'M': 'bgMagenta',
'C': 'bgCyan',
'W': 'bgWhite'
};
const log = (...messages) => {
const finalMessages = messages.map(m => {
if (typeof m !== 'string') {
return m;
}
const chunks = `${m.substr(0, 1) !== '´' ? '´w' : ''}${m}`.split('´');
chunks.shift();
return chunks.map(c => {
const colorCode = c.substr(0, 1);
const functionName = chalkMap[colorCode];
return chalk[functionName](c.substr(1));
}).join('');
});
console.log.apply(this, finalMessages);
};
module.exports = log;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment