<commit_before>'use strict';

const Profiler = require('../../stats/profiler-proxy');
const debug = require('debug')('windshaft:cartodb:stats');

module.exports = function profiler (options) {
    const { enabled = true, statsClient } = options;

    return function profilerMiddleware (req, res, next) {
        const { logger } = res.locals;
        const { id } = logger.bindings();

        // TODO: stop using profiler and log stats instead of adding them to the profiler
        req.profiler = new Profiler({
            statsd_client: statsClient,
            profile: enabled
        });

        req.profiler.start(id);

        res.on('finish', () => {
            req.profiler.done('response');
            logger.info({ stats: req.profiler.toJSON() });

            try {
                // May throw due to dns, see: http://github.com/CartoDB/Windshaft/issues/166
                req.profiler.sendStats();
            } catch (err) {
                debug('error sending profiling stats: ' + err);
            }
        });

        next();
    };
};
<commit_msg>Don't create a new metric for each request, use the same label to send to statsd<commit_after>'use strict';

const Profiler = require('../../stats/profiler-proxy');
const debug = require('debug')('windshaft:cartodb:stats');
const { name: prefix } = require('../../../package.json');

module.exports = function profiler (options) {
    const { enabled = true, statsClient } = options;

    return function profilerMiddleware (req, res, next) {
        const { logger } = res.locals;

        // TODO: stop using profiler and log stats instead of adding them to the profiler
        req.profiler = new Profiler({
            statsd_client: statsClient,
            profile: enabled
        });

        req.profiler.start(prefix);

        res.on('finish', () => {
            req.profiler.done('response');
            logger.info({ stats: req.profiler.toJSON() });

            try {
                // May throw due to dns, see: http://github.com/CartoDB/Windshaft/issues/166
                req.profiler.sendStats();
            } catch (err) {
                debug('error sending profiling stats: ' + err);
            }
        });

        next();
    };
};

{'fraction_non_alphanumeric': 0.13660714285714284, 'fraction_numerical': 0.0026785714285714286, 'mean_word_length': 2.0202156334231804, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6062989', 'n_tokens_mistral': 632, 'n_tokens_neox': 620, 'n_words': 162}