Use standard serializers for error, request, and response

This commit is contained in:
Daniel García Aubert 2020-06-03 14:28:35 +02:00
parent 29c6505252
commit 1e89821d97
3 changed files with 11 additions and 5 deletions

View File

@ -9,6 +9,7 @@ module.exports = function errorMiddleware (/* options */) {
allErrors = populateLimitErrors(allErrors); allErrors = populateLimitErrors(allErrors);
// TODO REMOVE THIS THREE LINES PLEASE
const label = err.label || 'UNKNOWN'; const label = err.label || 'UNKNOWN';
err = allErrors[0] || new Error(label); err = allErrors[0] || new Error(label);
allErrors[0] = err; allErrors[0] = err;
@ -20,8 +21,8 @@ module.exports = function errorMiddleware (/* options */) {
statusCode = 200; statusCode = 200;
} }
allErrors.forEach((err) => debug('[%s ERROR] -- %d: %s, %s', label, statusCode, err, err.stack)); allErrors.forEach((err) => debug('[%s ERROR] -- %d: %s, %s', err.label || 'UNKNOWN', statusCode, err, err.stack));
allErrors.forEach((err) => logger.error(err)); logger.error({ errors: allErrors });
var errorResponseBody = { var errorResponseBody = {
errors: allErrors.map(errorMessage), errors: allErrors.map(errorMessage),

View File

@ -7,8 +7,8 @@ module.exports = function initLogger ({ logger }) {
const id = req.get('X-Request-Id') || uuid.v4(); const id = req.get('X-Request-Id') || uuid.v4();
res.locals.logger = logger.child({ id }); res.locals.logger = logger.child({ id });
res.locals.logger.info(req); res.locals.logger.info({ request: req });
res.on('finish', () => res.locals.logger.info(res)); res.on('finish', () => res.locals.logger.info({ response: res }));
next(); next();
}; };

View File

@ -8,7 +8,12 @@ module.exports = class Logger {
const logLevelFromNodeEnv = NODE_ENV === 'test' ? 'fatal' : 'info'; const logLevelFromNodeEnv = NODE_ENV === 'test' ? 'fatal' : 'info';
const options = { const options = {
base: null, // Do not bind hostname, pid and friends by default base: null, // Do not bind hostname, pid and friends by default
level: LOG_LEVEL || logLevelFromNodeEnv level: LOG_LEVEL || logLevelFromNodeEnv,
serializers: {
request: pino.stdSerializers.req,
response: pino.stdSerializers.res,
errors: (errors) => errors.map((err) => pino.stdSerializers.err(err))
}
}; };
const dest = pino.destination({ sync: false }); // stdout const dest = pino.destination({ sync: false }); // stdout