-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
79 lines (72 loc) · 1.92 KB
/
index.js
File metadata and controls
79 lines (72 loc) · 1.92 KB
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
/* global console, module */
/* eslint no-console: "off" */
/* eslint guard-for-in: "off" */
const callbacks = {};
let configuration = {
debug: true,
error: true,
info: true,
log: true,
logger: console.log,
warn: true,
};
const parseValue = (value) => {
const parseObject = (obj, seen) => {
if (!obj) return obj;
if (typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
return obj.map((p) => parseObject(p, [...seen, p]));
}
if (obj instanceof Date) {
return obj.toISOString();
}
const result = {};
if (obj.constructor && obj.constructor.name && obj.constructor.name.endsWith('Error')) {
result.error = obj.constructor.name;
result.message = obj.message;
result.stack = obj.stack;
}
Object.keys(obj).forEach((key) => {
result[key] = seen.includes(obj[key]) ? '<circular>' : parseObject(obj[key], [...seen, obj[key]]);
});
return result;
};
return parseObject(value, [value]);
};
const logJSON = (level, ...values) => {
if (!configuration[level]) return null;
let message = '';
if (values.length === 1) {
message = parseValue(values[0]);
}
if (values.length > 1) {
message = values.map((v) => parseValue(v));
}
const json = JSON.stringify({
level: level.toUpperCase(),
message,
});
configuration.logger(json);
if (callbacks[level]) {
callbacks[level](json);
}
return json;
};
const on = (level, callback) => {
if (typeof callback === 'function') {
callbacks[level] = callback;
}
};
module.exports = {
debug: (...values) => logJSON('debug', ...values),
error: (...values) => logJSON('error', ...values),
info: (...values) => logJSON('info', ...values),
log: (...values) => logJSON('log', ...values),
on,
setConfiguration: (newConfiguration) => {
configuration = { ...configuration, ...newConfiguration };
},
warn: (...values) => logJSON('warn', ...values),
};