Ghost/core/server/web/shared/middlewares/log-request.js
Rishabh Garg fcd275f6c0 Refactored web/middleware and web/utils to web/shared (#9892)
refs #9866

- Moved web/middleware to web/shared/middlewares
- Moved util file to web/shared/utils
2018-09-20 20:04:34 +02:00

31 lines
880 B
JavaScript

const uuid = require('uuid');
const common = require('../../../lib/common');
/**
* @TODO:
* - move middleware to ignition?
*/
module.exports = function logRequest(req, res, next) {
const startTime = Date.now(),
requestId = req.get('X-Request-ID') || uuid.v1();
function logResponse() {
res.responseTime = (Date.now() - startTime) + 'ms';
req.requestId = requestId;
req.userId = req.user ? (req.user.id ? req.user.id : req.user) : null;
if (req.err && req.err.statusCode !== 404) {
common.logging.error({req: req, res: res, err: req.err});
} else {
common.logging.info({req: req, res: res});
}
res.removeListener('finish', logResponse);
res.removeListener('close', logResponse);
}
res.on('finish', logResponse);
res.on('close', logResponse);
next();
};