overleaf/services/filestore/app/js/RequestLogger.js

62 lines
1.4 KiB
JavaScript
Raw Normal View History

const logger = require('@overleaf/logger')
const metrics = require('@overleaf/metrics')
2020-01-14 07:02:39 -05:00
class RequestLogger {
constructor() {
this._logInfo = {}
this._logMessage = 'http request'
}
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) {
req.requestLogger.addFields({ error: err })
res.status(500).send(err.message)
}
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-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-14 07:02:39 -05:00
const responseTime = new Date() - startTime
2020-01-14 07:02:39 -05:00
const routePath = req.route && req.route.path.toString()
2020-01-14 07:02:39 -05:00
if (routePath) {
metrics.timing('http_request', responseTime, null, {
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' : 'debug'
2020-01-14 07:02:39 -05:00
logger[level](
{
req,
res,
responseTimeMs: responseTime,
2021-07-13 07:04:46 -04:00
info: req.requestLogger._logInfo,
},
2020-01-14 12:13:12 -05:00
req.requestLogger._logMessage
2020-01-14 07:02:39 -05:00
)
}
2020-01-14 07:02:39 -05:00
next()
}
}
2020-01-14 07:02:39 -05:00
module.exports = RequestLogger