Created
April 29, 2020 05:00
-
-
Save dwaps/6ff1a49f09ad0f9526365d609af46ccf to your computer and use it in GitHub Desktop.
JS: TP création d'une classe pour afficher de simples logs stylisés.
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
/** | |
* Override of console.log: just another way to display log with style. | |
* | |
* @author Michael CORNILLON <ei.dwaps@gmail.com> | |
* @version 1.0 | |
*/ | |
export default class Logger { | |
/** | |
* Initilize properties for log message and its style(s) | |
* | |
* @constructor | |
* @param {...string} logs Even params = log / Odd params = style | |
*/ | |
constructor(...logs) { | |
this.consoleLog = ''; | |
this.consoleStyleLog = []; | |
if (logs.length > 0) this.initAndDisplay(...logs); | |
} | |
/** | |
* Create an array for log messages and another for styles, to build only one log with correct %c locations. | |
* | |
* @method | |
* @param {...string} logs Even params = log / Odd params = style | |
*/ | |
initAndDisplay(...logs) { | |
const logsTab = []; | |
this.consoleStyleLog = logs.filter((log, i) => { | |
const isStyle = !!(i % 2); | |
if (!isStyle) logsTab.push(log); | |
return isStyle; | |
}); | |
logsTab.forEach(log => this.consoleLog += '%c' + log); | |
this.display(); | |
} | |
/** | |
* Return a string --> css style for an error displayed by console.log. | |
*/ | |
get errorDefaultStyle() { | |
return 'background:red;color:white;'; | |
} | |
/** | |
* Return a string of default css style of console.log. | |
*/ | |
get logDefaultStyle() { | |
return 'background:green;color:white;'; | |
} | |
/** | |
* Do a console.log correctly formatted. | |
* | |
* @method | |
*/ | |
display() { | |
console.log(this.consoleLog, ...this.consoleStyleLog); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment