codecombat/server/commons/perfmon.coffee

44 lines
1.2 KiB
CoffeeScript
Raw Normal View History

fs = require 'fs'
path = require 'path'
config = require '../../server_config'
StatsD = require 'node-statsd'
if config.statsd
2015-11-17 18:19:17 -05:00
realClient = new StatsD(config.statsd)
else
2015-11-17 18:19:17 -05:00
mock = new StatsD(mock: true)
exports.client = realClient or mock
exports.middleware = (req, res, next) ->
2015-11-17 18:19:17 -05:00
req.statsd = exports.client
if realClient
time = process.hrtime();
cleanup = ->
res.removeListener 'finish', recordMetrics
res.removeListener 'error', cleanup
res.removeListener 'close', cleanup
2015-11-17 18:19:17 -05:00
recordMetrics = ->
diff = process.hrtime(time);
ms = (diff[0] * 1000 + diff[1] / 1e6);
path = req.route?.path or '/*'
stat = req.method + "." + path.replace /[^A-Za-z0-9]+/g, '_'
realClient.timing stat, ms
2015-12-02 13:58:02 -05:00
name = req.user?._id
realClient.unique 'users', name if name
2015-11-17 18:19:17 -05:00
res.once 'finish', recordMetrics
res.once 'error', cleanup
res.once 'close', cleanup
else
req.statsd = mock
2015-11-17 18:19:17 -05:00
next() unless not next
exports.trace = (name, callback) ->
2015-11-17 18:19:17 -05:00
return callback unless realClient
time = process.hrtime()
(args...) ->
2015-12-02 13:58:02 -05:00
realClient.timing name.replace(/[^A-Za-z0-9]+/g, '_'), ms
2015-11-17 18:19:17 -05:00
return callback.apply(this, args)