2018-10-23 23:45:42 +08:00
|
|
|
'use strict';
|
|
|
|
|
2019-10-07 16:01:18 +08:00
|
|
|
const Profiler = require('../../stats/profiler-proxy');
|
2017-10-05 23:06:31 +08:00
|
|
|
const debug = require('debug')('windshaft:cartodb:stats');
|
2020-06-10 23:21:35 +08:00
|
|
|
const { name: prefix } = require('../../../package.json');
|
2017-10-05 23:06:31 +08:00
|
|
|
|
2020-06-02 23:09:06 +08:00
|
|
|
module.exports = function profiler (options) {
|
2017-10-05 23:06:31 +08:00
|
|
|
const { enabled = true, statsClient } = options;
|
|
|
|
|
2020-06-02 23:09:06 +08:00
|
|
|
return function profilerMiddleware (req, res, next) {
|
|
|
|
const { logger } = res.locals;
|
|
|
|
|
2020-06-04 18:10:15 +08:00
|
|
|
// TODO: stop using profiler and log stats instead of adding them to the profiler
|
2017-10-05 23:06:31 +08:00
|
|
|
req.profiler = new Profiler({
|
|
|
|
statsd_client: statsClient,
|
|
|
|
profile: enabled
|
|
|
|
});
|
|
|
|
|
2020-06-10 23:21:35 +08:00
|
|
|
req.profiler.start(prefix);
|
2020-06-04 01:51:56 +08:00
|
|
|
|
2017-10-08 01:02:26 +08:00
|
|
|
res.on('finish', () => {
|
2020-06-04 01:51:56 +08:00
|
|
|
req.profiler.done('response');
|
2020-06-02 23:09:06 +08:00
|
|
|
logger.info({ stats: req.profiler.toJSON() });
|
|
|
|
|
2017-10-08 01:02:26 +08:00
|
|
|
try {
|
|
|
|
// May throw due to dns, see: http://github.com/CartoDB/Windshaft/issues/166
|
|
|
|
req.profiler.sendStats();
|
|
|
|
} catch (err) {
|
2019-10-22 01:07:24 +08:00
|
|
|
debug('error sending profiling stats: ' + err);
|
2017-10-08 01:02:26 +08:00
|
|
|
}
|
2017-10-05 23:06:31 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
next();
|
|
|
|
};
|
2017-10-08 01:16:15 +08:00
|
|
|
};
|