2020-06-02 17:49:54 +08:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const pino = require('pino');
|
2020-06-05 02:28:06 +08:00
|
|
|
const { req: requestSerializer, res: responseSerializer, err, wrapErrorSerializer } = pino.stdSerializers;
|
|
|
|
const DEV_ENVS = ['test', 'development'];
|
2020-06-02 17:49:54 +08:00
|
|
|
|
|
|
|
module.exports = class Logger {
|
|
|
|
constructor () {
|
|
|
|
const { LOG_LEVEL, NODE_ENV } = process.env;
|
2020-06-02 19:16:26 +08:00
|
|
|
const logLevelFromNodeEnv = NODE_ENV === 'test' ? 'fatal' : 'info';
|
2020-06-05 02:28:06 +08:00
|
|
|
const errorSerializer = DEV_ENVS.includes(NODE_ENV) ? err : wrapErrorSerializer(err => {
|
2020-09-09 17:29:32 +08:00
|
|
|
if (err.hasOwnProperty('stack')) {
|
|
|
|
err.stack = err.stack.split('\n').slice(0, 3).join('\n');
|
|
|
|
}
|
2020-06-05 02:28:06 +08:00
|
|
|
return err;
|
|
|
|
});
|
2020-06-02 17:49:54 +08:00
|
|
|
const options = {
|
|
|
|
base: null, // Do not bind hostname, pid and friends by default
|
2020-06-03 20:28:35 +08:00
|
|
|
level: LOG_LEVEL || logLevelFromNodeEnv,
|
2020-07-21 22:36:23 +08:00
|
|
|
formatters: {
|
|
|
|
level (label) {
|
|
|
|
if (label === 'warn') {
|
2020-07-21 23:09:19 +08:00
|
|
|
return { levelname: 'warning' };
|
2020-07-21 22:36:23 +08:00
|
|
|
}
|
|
|
|
|
2020-07-21 23:09:19 +08:00
|
|
|
return { levelname: label };
|
2020-07-21 22:36:23 +08:00
|
|
|
}
|
|
|
|
},
|
2020-07-23 20:01:34 +08:00
|
|
|
messageKey: 'event_message',
|
2020-07-21 22:36:23 +08:00
|
|
|
timestamp: () => `,"timestamp":"${new Date(Date.now()).toISOString()}"`,
|
2020-06-03 20:28:35 +08:00
|
|
|
serializers: {
|
2020-07-21 22:36:23 +08:00
|
|
|
client_request: requestSerializer,
|
|
|
|
server_response: responseSerializer,
|
2020-07-21 23:53:46 +08:00
|
|
|
exception: errorSerializer
|
2020-06-03 20:28:35 +08:00
|
|
|
}
|
2020-06-02 17:49:54 +08:00
|
|
|
};
|
2020-06-02 19:16:26 +08:00
|
|
|
const dest = pino.destination({ sync: false }); // stdout
|
2020-06-02 17:49:54 +08:00
|
|
|
|
|
|
|
this._logger = pino(options, dest);
|
|
|
|
}
|
|
|
|
|
|
|
|
trace (...args) {
|
|
|
|
this._logger.trace(...args);
|
|
|
|
}
|
|
|
|
|
|
|
|
debug (...args) {
|
|
|
|
this._logger.debug(...args);
|
|
|
|
}
|
|
|
|
|
|
|
|
info (...args) {
|
|
|
|
this._logger.info(...args);
|
|
|
|
}
|
|
|
|
|
|
|
|
warn (...args) {
|
|
|
|
this._logger.warn(...args);
|
|
|
|
}
|
|
|
|
|
|
|
|
error (...args) {
|
|
|
|
this._logger.error(...args);
|
|
|
|
}
|
|
|
|
|
|
|
|
fatal (...args) {
|
|
|
|
this._logger.fatal(...args);
|
|
|
|
}
|
|
|
|
|
|
|
|
child (...args) {
|
|
|
|
return this._logger.child(...args);
|
|
|
|
}
|
|
|
|
|
|
|
|
finish (callback) {
|
|
|
|
return pino.final(this._logger, callback);
|
|
|
|
}
|
|
|
|
};
|