forked from segmentio/analytics-node
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathLogger.js
78 lines (64 loc) · 1.6 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
const LOG_MSG_PREFIX = 'Rudder';
const LOG_LEVEL_MAP = {
log: 0,
debug: 1,
info: 2,
warn: 3,
error: 4,
none: 5,
};
/**
* Service to log messages/data to output provider, default is console
*/
class Logger {
constructor(minLogLevel = 4) {
this.minLogLevel = minLogLevel;
this.logProvider = console;
}
log(...data) {
this.outputLog('log', data);
}
info(...data) {
this.outputLog('info', data);
}
debug(...data) {
this.outputLog('debug', data);
}
warn(...data) {
this.outputLog('warn', data);
}
error(...data) {
this.outputLog('error', data);
}
outputLog(logMethod, data) {
if (this.minLogLevel <= LOG_LEVEL_MAP[logMethod]) {
this.logProvider[logMethod.toLowerCase()](...this.formatLogData(logMethod, data));
}
}
/**
* Formats the console message
*/
// eslint-disable-next-line class-methods-use-this
formatLogData(level, data) {
if (Array.isArray(data) && data.length > 0) {
// trim whitespaces for original message
const originalMsg = typeof data[0] === 'string' ? data[0].trim() : '';
// prepare the final message
const timestamp = new Date().toISOString();
const msg = `${timestamp} [${LOG_MSG_PREFIX}] ${level}: ${originalMsg}`;
const styledLogArgs = [msg];
// add first it if it was not a string msg
if (typeof data[0] !== 'string') {
styledLogArgs.push(data[0]);
}
// append rest of the original arguments
styledLogArgs.push(...data.slice(1));
return styledLogArgs;
}
return data;
}
}
module.exports = {
Logger,
LOG_LEVEL_MAP,
};