2020-06-06 02:12:20 +08:00
|
|
|
'use strict'
|
|
|
|
|
|
|
|
const split = require('split2');
|
|
|
|
const assingDeep = require('assign-deep');
|
2020-06-09 02:16:00 +08:00
|
|
|
const { Transform } = require('stream');
|
2020-06-08 22:34:08 +08:00
|
|
|
const DEV_ENVS = ['test', 'development'];
|
|
|
|
const logs = new Map();
|
2020-06-06 02:12:20 +08:00
|
|
|
|
|
|
|
const LEVELS = {
|
|
|
|
10: 'trace',
|
|
|
|
20: 'debug',
|
|
|
|
30: 'info',
|
|
|
|
40: 'warn',
|
|
|
|
50: 'error',
|
|
|
|
60: 'fatal'
|
|
|
|
}
|
|
|
|
|
2020-06-09 02:16:00 +08:00
|
|
|
module.exports = function logCollector () {
|
2020-06-06 02:12:20 +08:00
|
|
|
return new Transform({
|
2020-06-09 02:16:00 +08:00
|
|
|
transform (chunk, enc, callback) {
|
2020-06-06 02:12:20 +08:00
|
|
|
let entry;
|
|
|
|
|
|
|
|
try {
|
|
|
|
entry = JSON.parse(chunk);
|
2020-06-08 22:34:08 +08:00
|
|
|
const { level, time } = entry;
|
|
|
|
|
|
|
|
if (level === undefined && time === undefined) {
|
2020-06-09 16:00:54 +08:00
|
|
|
throw new Error('Entry log is not valid');
|
2020-06-08 22:34:08 +08:00
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
if (DEV_ENVS.includes(process.env.NODE_ENV)) {
|
|
|
|
this.push(chunk + '\n');
|
|
|
|
}
|
2020-06-06 02:12:20 +08:00
|
|
|
return callback();
|
|
|
|
}
|
|
|
|
|
|
|
|
const { id, end } = entry;
|
|
|
|
|
|
|
|
if (id === undefined) {
|
|
|
|
entry.level = LEVELS[entry.level];
|
|
|
|
this.push(`${JSON.stringify(entry)}\n`);
|
|
|
|
return callback();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (end === true) {
|
|
|
|
const accEntry = logs.get(id);
|
|
|
|
accEntry.level = LEVELS[accEntry.level];
|
|
|
|
accEntry.time = entry.time;
|
|
|
|
this.push(`${JSON.stringify(accEntry)}\n`);
|
|
|
|
logs.delete(id);
|
|
|
|
return callback();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (logs.has(id)) {
|
|
|
|
const accEntry = logs.get(id);
|
|
|
|
|
|
|
|
if (accEntry.level > entry.level) {
|
|
|
|
delete entry.level
|
|
|
|
}
|
|
|
|
|
|
|
|
let error;
|
2020-06-08 22:34:08 +08:00
|
|
|
if (hasProperty(accEntry, 'error') && hasProperty(entry, 'error')) {
|
2020-06-06 02:12:20 +08:00
|
|
|
logs.set(id, assingDeep({}, accEntry, entry, { error: accEntry.error.concat(entry.error) }));
|
|
|
|
} else {
|
|
|
|
logs.set(id, assingDeep({}, accEntry, entry));
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
logs.set(id, entry);
|
|
|
|
}
|
|
|
|
|
|
|
|
callback();
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-06-08 22:34:08 +08:00
|
|
|
function hasProperty(obj, prop) {
|
|
|
|
return Object.prototype.hasOwnProperty.call(obj, prop)
|
|
|
|
}
|