-
Notifications
You must be signed in to change notification settings - Fork 65
/
Logger.js
99 lines (74 loc) · 2.17 KB
/
Logger.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
exports = (module.exports = Logger);
exports.maybeApplyFormatSpecifier = maybeApplyFormatSpecifier;
exports.getFormatter = getFormatter;
exports.format = format;
function notImplemented() { throw new Error('not implemented'); };
const converters = {
'%s': function(a) { return '' + a; }, // string
'%d': function(a) { return Number.parseInt(a, 10); }, // integer
'%i': function(a) { return Number.parseInt(a, 10); }, // integer
'%f': function(a) { return Number.parseFloat(a, 10); }, // float
// these require a UI
'%o': notImplemented, // expandable DOM element
'%O': notImplemented, // expandable JS Object
'%c': notImplemented, // applies CSS
};
const specifier = Object.keys(converters);
const hasSpecifier = new RegExp('(' + specifier.join('|') + ')');
global.print = print;
const util = require('util');
function print(logLevel, ...args) {
const message = util.format(...args);
if (logLevel === 'error') {
process.stderr.write(message + '\n');
return;
}
if (logLevel === 'log' || logLevel === 'info' || logLevel === 'warn') {
process.stdout.write(message + '\n');
return;
}
}
function Logger(logLevel, ...args) {
if (args.length === 0) {
return;
}
args = maybeApplyFormatSpecifier(args);
global.print(logLevel, args);
}
function maybeApplyFormatSpecifier(args) {
if (args.length === 1) {
return args;
}
if (!hasSpecifier.test(args[0])) {
return args;
}
return format(args);
}
function format(args) {
const token = args[0].split('');
let rest;
let result;
for (let i = 0; i < (token.length - 1); i++) {
if (specifier.indexOf(token[i] + token[i + 1]) !== -1) {
const formatter = getFormatter(token[i] + token[i + 1]);
let formatted = args[0].replace(token[i] + token[i + 1], formatter(args[1]));
rest = args.slice(2);
result = [formatted, ...rest];
break;
}
}
if (!hasSpecifier.test(result)) {
return result;
}
if (result.length === 1) {
return result;
}
return format(result);
}
function getFormatter(specifier) {
function passThrough(a) { return a; };
if (!converters[specifier]) {
return passThrough;
}
return converters[specifier];
}