2018-10-24 21:42:33 +08:00
|
|
|
'use strict';
|
|
|
|
|
2019-10-04 00:24:39 +08:00
|
|
|
const Profiler = require('../../stats/profiler-proxy');
|
2020-06-30 23:42:59 +08:00
|
|
|
const { name: prefix } = require('../../../package.json');
|
2019-10-01 20:31:17 +08:00
|
|
|
|
|
|
|
module.exports = function profiler ({ statsClient }) {
|
|
|
|
return function profilerMiddleware (req, res, next) {
|
2020-06-30 23:42:59 +08:00
|
|
|
const start = new Date();
|
|
|
|
const { logger } = res.locals;
|
|
|
|
|
2019-10-01 20:31:17 +08:00
|
|
|
req.profiler = new Profiler({
|
|
|
|
profile: global.settings.useProfiler,
|
|
|
|
statsd_client: statsClient
|
|
|
|
});
|
|
|
|
|
2020-06-30 23:42:59 +08:00
|
|
|
req.profiler.start(prefix);
|
2018-02-19 22:13:36 +08:00
|
|
|
|
2020-06-30 23:42:59 +08:00
|
|
|
res.on('finish', () => {
|
|
|
|
req.profiler.add({ response: new Date() - start });
|
2018-02-19 22:13:36 +08:00
|
|
|
req.profiler.end();
|
2020-06-30 23:42:59 +08:00
|
|
|
logger.info({ stats: req.profiler.toJSON() });
|
2018-02-19 22:13:36 +08:00
|
|
|
|
2020-06-30 23:42:59 +08:00
|
|
|
try {
|
|
|
|
req.profiler.sendStats();
|
|
|
|
} catch (err) {
|
|
|
|
logger.warn({ error: err });
|
|
|
|
}
|
|
|
|
});
|
2018-02-19 22:13:36 +08:00
|
|
|
|
|
|
|
next();
|
|
|
|
};
|
|
|
|
};
|