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