From fd25902cbe0b91cfbd6a01cf33ba361f95a8e898 Mon Sep 17 00:00:00 2001 From: Pierre Burgy Date: Fri, 23 Jun 2017 18:50:52 +0200 Subject: [PATCH] Improve logger and responses policy --- .../configuration/hooks/core/logger/index.js | 7 +++- .../hooks/core/responses/policy.js | 39 +++++++++---------- 2 files changed, 25 insertions(+), 21 deletions(-) diff --git a/packages/strapi/lib/configuration/hooks/core/logger/index.js b/packages/strapi/lib/configuration/hooks/core/logger/index.js index 318356cdb3..fb235dc662 100644 --- a/packages/strapi/lib/configuration/hooks/core/logger/index.js +++ b/packages/strapi/lib/configuration/hooks/core/logger/index.js @@ -25,7 +25,12 @@ module.exports = strapi => { const start = new Date(); await next(); const ms = new Date() - start; - strapi.log.debug(ctx.method + ' ' + ctx.url + ' (' + ms + 'ms)'); + + // Choose logger type depending on the response status. + const logger = ctx.status < 400 ? strapi.log.debug : strapi.log.error; + + // Finally, log the string. + logger(`${ctx.ip} - [${start.toISOString()}] ${ctx.method} ${ctx.status} ${ctx.url} (${ms}ms)`); }); } diff --git a/packages/strapi/lib/configuration/hooks/core/responses/policy.js b/packages/strapi/lib/configuration/hooks/core/responses/policy.js index d52cca9340..96e32a8737 100644 --- a/packages/strapi/lib/configuration/hooks/core/responses/policy.js +++ b/packages/strapi/lib/configuration/hooks/core/responses/policy.js @@ -37,30 +37,29 @@ module.exports = async function(ctx, next) { }); try { + // App logic. await next(); - - // Set context when no route is matched. - if (_.get(ctx.request, 'route') === undefined) { - ctx.notFound(); - } - - if (_.get(ctx.body, 'isBoom') || _.isError(ctx.body)) { - ctx.throw(); - } } catch (error) { - // Error object could be also in the context body... - strapi.log.error(ctx.body || error); - // Wrap error into a Boom's response - const formattedError = _.get(ctx.body, 'isBoom') - ? ctx.body || error.message + // Log error. + strapi.log.error(error); + + // Wrap error into a Boom's response. + ctx.body = _.get(ctx.body, 'isBoom') + ? ctx.body || error && error.message : Boom.wrap(error, error.status, ctx.body || error.message); + } - ctx.status = formattedError.output.statusCode || error.status || 500; - ctx.body = formattedError.output.payload; + // Empty body is considered as `notFound` response. + if (!ctx.body) { + ctx.notFound(); + } - // Call custom responses. - if (_.isFunction(_.get(strapi.config, `responses.${ctx.status}`))) { - await strapi.config.responses[ctx.status].call(this, ctx); - } + // Format `ctx.body` and `ctx.status`. + ctx.status = ctx.body.isBoom ? ctx.body.output.statusCode : ctx.status; + ctx.body = ctx.body.isBoom ? ctx.body.output.payload : ctx.body; + + // Call custom responses. + if (_.isFunction(_.get(strapi.config, `responses.${ctx.status}`))) { + await strapi.config.responses[ctx.status].call(this, ctx); } };