2018-10-25 20:52:27 +02:00
|
|
|
const logger = require('winston');
|
2018-10-24 10:43:30 +02:00
|
|
|
const db = require('../models');
|
|
|
|
const httpContext = require('express-http-context');
|
|
|
|
|
|
|
|
function logMetricsMiddleware(req, res, next) {
|
|
|
|
res.on('finish', () => {
|
|
|
|
const userAgent = req.get('user-agent');
|
|
|
|
const routePath = httpContext.get('routePath');
|
|
|
|
|
2018-10-25 20:52:27 +02:00
|
|
|
let referrer = req.get('referrer');
|
|
|
|
|
2018-10-25 21:07:11 +02:00
|
|
|
if(referrer && referrer.length > 255) {
|
2018-11-09 16:55:19 +01:00
|
|
|
try {
|
|
|
|
// Attempt to "safely" clamp long URLs
|
|
|
|
referrer = /(.*?)#.*/.exec(referrer)[1];
|
|
|
|
} catch(e) {
|
|
|
|
// Cheap forced string conversion & clamp
|
|
|
|
referrer = new String(referrer);
|
|
|
|
referrer = referrer.substr(0, 255);
|
|
|
|
}
|
2018-10-25 20:52:27 +02:00
|
|
|
|
|
|
|
if(referrer.length > 255) {
|
|
|
|
logger.warn('Request refferer exceeds 255 characters:', referrer);
|
|
|
|
referrer = referrer.substring(0, 255);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-24 10:43:30 +02:00
|
|
|
db.Metrics.create({
|
|
|
|
time: Date.now(),
|
|
|
|
isInternal: /node\-fetch/.test(userAgent),
|
|
|
|
isChannel: res.isChannel,
|
|
|
|
claimId: res.claimId,
|
|
|
|
routePath: httpContext.get('routePath'),
|
|
|
|
params: JSON.stringify(req.params),
|
|
|
|
ip: req.headers['x-forwarded-for'] || req.connection.remoteAddress,
|
|
|
|
request: req.url,
|
|
|
|
routeData: JSON.stringify(httpContext.get('routeData')),
|
2018-10-25 20:52:27 +02:00
|
|
|
referrer,
|
2018-10-24 10:43:30 +02:00
|
|
|
userAgent,
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
next();
|
|
|
|
}
|
|
|
|
|
|
|
|
function setRouteDataInContextMiddleware(routePath, routeData) {
|
|
|
|
return function (req, res, next) {
|
|
|
|
httpContext.set('routePath', routePath);
|
|
|
|
httpContext.set('routeData', routeData);
|
|
|
|
next();
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
logMetricsMiddleware,
|
|
|
|
setRouteDataInContextMiddleware,
|
|
|
|
};
|