1 | const util = require('util');
|
2 | const color = require('bash-color');
|
3 |
|
4 | const LEVELS = {
|
5 | DEBUG: 0,
|
6 | INFO: 1,
|
7 | WARN: 2,
|
8 | ERROR: 3
|
9 | }
|
10 |
|
11 | const COLORS = {
|
12 | DEBUG: color.purple,
|
13 | INFO: color.cyan,
|
14 | WARN: color.yellow,
|
15 | ERROR: color.red
|
16 | }
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | class logger {
|
28 | constructor(logLevel) {
|
29 | this.lastChar = "\n";
|
30 | this.levelsByValue = {};
|
31 | this.setLevel(logLevel || 'info');
|
32 | for (let levelKey in LEVELS) {
|
33 | let level = LEVELS[levelKey];
|
34 | levelKey = levelKey.toLowerCase();
|
35 | this[levelKey] = (...args) => {
|
36 | args.unshift(level);
|
37 | this._logLn.apply(this, args)
|
38 | }
|
39 | this.levelsByValue[level] = levelKey.toUpperCase();
|
40 | }
|
41 | }
|
42 |
|
43 | _stdout(msg){
|
44 | process.stdout.write(msg);
|
45 | }
|
46 |
|
47 | setLevel(logLevel) {
|
48 | logLevel = logLevel || 'INFO';
|
49 | this.logLevel = LEVELS[logLevel.toUpperCase()];
|
50 | }
|
51 |
|
52 | getLevel(logLevel) {
|
53 | return this.logLevel;
|
54 | }
|
55 |
|
56 | _write(msg) {
|
57 | msg = msg.toString();
|
58 | this.lastChar = msg[msg.length - 1];
|
59 | return this._stdout(msg);
|
60 | }
|
61 |
|
62 | _format() {
|
63 | return util.format.apply(util, arguments)
|
64 | }
|
65 |
|
66 | _log(level, ...args) {
|
67 | if (level < this.logLevel) return;
|
68 | let levelKey = this.levelsByValue[level];
|
69 | let msg = this._format.apply(util, args);
|
70 |
|
71 | if (this.lastChar == '\n') {
|
72 | msg = COLORS[levelKey](levelKey.toLowerCase() + ':') + ' ' + msg;
|
73 | }
|
74 | return this._write(msg);
|
75 | }
|
76 |
|
77 | ok(...args) {
|
78 | let msg = this._format.apply(util, args);
|
79 | if (args.length > 0) {
|
80 | this._logLn(LEVELS.INFO, color.green('>> ') + msg.trim().replace(/\n/g, color.green('\n>> ')), color.green('OK'));
|
81 | } else {
|
82 | this._log(LEVELS.INFO, color.green('OK'), '\n');
|
83 | }
|
84 | }
|
85 |
|
86 | _logLn(...args) {
|
87 | if (this.lastChar != '\n') this._write('\n');
|
88 | args.push('\n');
|
89 | return this._log.apply(this, args);
|
90 | }
|
91 | }
|
92 |
|
93 | module.exports = logger; |
\ | No newline at end of file |