2021-12-14 08:00:35 -05:00
|
|
|
const logger = require('@overleaf/logger')
|
2020-11-25 06:57:23 -05:00
|
|
|
const metrics = require('@overleaf/metrics')
|
2020-01-07 16:19:26 -05:00
|
|
|
|
2020-01-14 07:02:39 -05:00
|
|
|
class RequestLogger {
|
|
|
|
constructor() {
|
|
|
|
this._logInfo = {}
|
|
|
|
this._logMessage = 'http request'
|
|
|
|
}
|
2020-01-07 16:19:26 -05:00
|
|
|
|
2020-01-14 12:13:12 -05:00
|
|
|
addFields(fields) {
|
|
|
|
Object.assign(this._logInfo, fields)
|
|
|
|
}
|
|
|
|
|
|
|
|
setMessage(message) {
|
|
|
|
this._logMessage = message
|
|
|
|
}
|
|
|
|
|
|
|
|
static errorHandler(err, req, res, next) {
|
2020-02-14 05:50:52 -05:00
|
|
|
req.requestLogger.addFields({ error: err })
|
2020-04-03 11:57:33 -04:00
|
|
|
res.status(500).send(err.message)
|
2020-01-10 12:08:47 -05:00
|
|
|
}
|
2020-01-14 07:02:39 -05:00
|
|
|
|
2020-01-14 12:13:12 -05:00
|
|
|
static middleware(req, res, next) {
|
2020-01-14 07:02:39 -05:00
|
|
|
const startTime = new Date()
|
2020-01-14 12:13:12 -05:00
|
|
|
req.requestLogger = new RequestLogger()
|
2020-01-10 12:08:47 -05:00
|
|
|
|
2020-01-14 07:02:39 -05:00
|
|
|
// override the 'end' method to log and record metrics
|
|
|
|
const end = res.end
|
2020-08-10 12:01:12 -04:00
|
|
|
res.end = function () {
|
2020-01-14 07:02:39 -05:00
|
|
|
// apply the standard request 'end' method before logging and metrics
|
|
|
|
end.apply(this, arguments)
|
2020-01-10 12:08:47 -05:00
|
|
|
|
2020-01-14 07:02:39 -05:00
|
|
|
const responseTime = new Date() - startTime
|
2020-01-10 12:08:47 -05:00
|
|
|
|
2020-01-14 07:02:39 -05:00
|
|
|
const routePath = req.route && req.route.path.toString()
|
2020-01-10 12:08:47 -05:00
|
|
|
|
2020-01-14 07:02:39 -05:00
|
|
|
if (routePath) {
|
|
|
|
metrics.timing('http_request', responseTime, null, {
|
2020-01-10 12:08:47 -05:00
|
|
|
method: req.method,
|
2020-01-14 07:02:39 -05:00
|
|
|
status_code: res.statusCode,
|
2021-07-13 07:04:46 -04:00
|
|
|
path: routePath.replace(/\//g, '_').replace(/:/g, '').slice(1),
|
2020-01-14 07:02:39 -05:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
const level = res.statusCode >= 500 ? 'err' : 'log'
|
|
|
|
logger[level](
|
|
|
|
{
|
2022-01-10 09:51:38 -05:00
|
|
|
req,
|
|
|
|
res,
|
|
|
|
responseTimeMs: responseTime,
|
2021-07-13 07:04:46 -04:00
|
|
|
info: req.requestLogger._logInfo,
|
2020-01-10 12:08:47 -05:00
|
|
|
},
|
2020-01-14 12:13:12 -05:00
|
|
|
req.requestLogger._logMessage
|
2020-01-14 07:02:39 -05:00
|
|
|
)
|
|
|
|
}
|
2020-01-10 12:08:47 -05:00
|
|
|
|
2020-01-14 07:02:39 -05:00
|
|
|
next()
|
|
|
|
}
|
2020-01-07 16:19:26 -05:00
|
|
|
}
|
2020-01-14 07:02:39 -05:00
|
|
|
|
|
|
|
module.exports = RequestLogger
|