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

78 lines
2.1 KiB
JavaScript
Raw Normal View History

const logger = require('logger-sharelatex')
const metrics = require('@overleaf/metrics')
2020-01-14 12:02:39 +00:00
class RequestLogger {
constructor() {
this._logInfo = {}
this._logMessage = 'http request'
}
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) {
req.requestLogger.addFields({ error: err })
res.status(500).send(err.message)
}
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-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-14 12:02:39 +00:00
const responseTime = new Date() - startTime
2020-01-14 12:02:39 +00:00
const routePath = req.route && req.route.path.toString()
2020-01-14 12:02:39 +00:00
if (routePath) {
metrics.timing('http_request', responseTime, null, {
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
})
}
const level = res.statusCode >= 500 ? 'err' : 'log'
logger[level](
{
req: {
url: req.originalUrl || req.url,
route: routePath,
method: req.method,
referrer: req.headers.referer || req.headers.referrer,
'remote-addr':
req.ip ||
(req.socket && req.socket.remoteAddress) ||
(req.socket &&
req.socket.socket &&
req.socket.socket.remoteAddress),
'user-agent': req.headers['user-agent'],
2021-07-13 11:04:46 +00:00
'content-length': req.headers['content-length'],
2020-01-14 12:02:39 +00:00
},
res: {
'content-length': res._headers['content-length'],
statusCode: res.statusCode,
2021-07-13 11:04:46 +00:00
'response-time': responseTime,
2020-01-14 12:02:39 +00:00
},
2021-07-13 11:04:46 +00:00
info: req.requestLogger._logInfo,
},
2020-01-14 17:13:12 +00:00
req.requestLogger._logMessage
2020-01-14 12:02:39 +00:00
)
}
2020-01-14 12:02:39 +00:00
next()
}
}
2020-01-14 12:02:39 +00:00
module.exports = RequestLogger