James Allen 12 лет назад
Сommit
42b500263a

+ 1 - 0
libraries/metrics/.gitignore

@@ -0,0 +1 @@
+node_modules

+ 2 - 0
libraries/metrics/index.js

@@ -0,0 +1,2 @@
+require("coffee-script")
+module.exports = require('./metrics');

+ 34 - 0
libraries/metrics/metrics.coffee

@@ -0,0 +1,34 @@
+StatsD = require('lynx')
+statsd = new StatsD('localhost', 8125, {on_error:->})
+
+name = "unknown"
+
+buildKey = (key)-> "#{name}.#{process.env.NODE_ENV or "development"}.#{key}"
+
+module.exports =
+	initialize: (options = {}) ->
+		name = options.name
+
+	set : (key, value, sampleRate = 1)->
+		statsd.set buildKey(key), value, sampleRate
+
+	inc : (key, sampleRate = 1)->
+		statsd.increment buildKey(key), sampleRate
+
+	timing: (key, timeSpan, sampleRate)->
+		statsd.timing(key, timeSpan, sampleRate)
+
+	Timer : class
+		constructor :(key, sampleRate = 1)->
+			this.start = new Date()
+			this.key = buildKey(key)
+			this.sampleRate = sampleRate
+		done:->
+			timeSpan = new Date - this.start
+			statsd.timing(this.key, timeSpan, this.sampleRate)
+
+	gauge : (key, value, sampleRate = 1)->
+		statsd.gauge key, value, sampleRate
+
+	mongodb: require "./mongodb"
+

+ 40 - 0
libraries/metrics/mongodb.coffee

@@ -0,0 +1,40 @@
+_ = require("underscore")
+
+module.exports =
+	monitor: (mongodb_require_path, logger) ->
+		Db = require("#{mongodb_require_path}/lib/mongodb/db").Db
+
+		Metrics = require("./metrics")
+
+		monitorMethod = (base, method, type) ->
+			_method = base[method]
+
+			base[method] = (db_command, options, callback) ->
+				if (typeof callback == 'undefined')
+					callback = options
+					options = {}
+					callback = () ->
+
+				key = "mongo-requests.#{type}"
+				if db_command.query?
+					query = Object.keys(db_command.query).sort().join("_")
+					key += "." + query
+
+				Metrics.inc key
+				timer = new Metrics.Timer(key)
+				start = new Date()
+				_method.call this, db_command, options, () ->
+					timer.done()
+					time = new Date() - start
+					logger.log
+						query: db_command.query
+						type: type
+						collection: db_command.collectionName
+						"response-time": new Date() - start
+						"mongo request"
+					callback.apply this, arguments
+
+		monitorMethod(Db.prototype, "_executeQueryCommand",  "query")
+		monitorMethod(Db.prototype, "_executeRemoveCommand", "remove")
+		monitorMethod(Db.prototype, "_executeInsertCommand", "insert")
+		monitorMethod(Db.prototype, "_executeUpdateCommand", "update")

+ 10 - 0
libraries/metrics/package.json

@@ -0,0 +1,10 @@
+{
+  "name": "metrics-sharelatex",
+  "version": "0.0.0",
+  "description": "A drop-in metrics and monitoring module for node.js apps",
+  "dependencies": {
+    "lynx": "~0.1.1",
+    "coffee-script": "~1.7.1",
+    "underscore": "~1.6.0"
+  }
+}