-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (72 loc) · 1.81 KB
/
index.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
/* eslint no-console: "off" */
const callbacks = {};
let configuration = {
log: true,
debug: true,
info: true,
warn: true,
error: true,
logger: console.log,
};
const parseValue = (value) => {
if (value && typeof value === 'object' && value.constructor && value.constructor.name && value.constructor.name.endsWith('Error')) {
const error = {
error: value.constructor.name,
message: value.message,
stack: value.stack,
};
Object.keys(value).forEach((key) => {
error[key] = value[key];
});
return error;
}
return 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 objects = [];
const json = JSON.stringify(
{
level: level.toUpperCase(),
message,
// timestamp: new Date().toISOString(),
},
(key, value) => {
// Filtering out properties
if (typeof value === 'object') {
if (objects.includes(value)) return 'object';
objects.push(value);
return value;
}
return value;
},
);
configuration.logger(json);
if (callbacks[level]) {
callbacks[level](json);
}
return json;
};
const on = (level, callback) => {
if (typeof callback === 'function') {
callbacks[level] = callback;
}
};
module.exports = {
on,
setConfiguration: (newConfiguration) => {
configuration = { ...configuration, ...newConfiguration };
},
log: (...values) => logJSON('log', ...values),
debug: (...values) => logJSON('debug', ...values),
info: (...values) => logJSON('info', ...values),
warn: (...values) => logJSON('warn', ...values),
error: (...values) => logJSON('error', ...values),
};