2017-03-15 15:06:54 +00:00
|
|
|
|
2017-03-17 11:47:38 +00:00
|
|
|
module.exports = (obj, methodName, prefix, logger) ->
|
2017-03-15 15:06:54 +00:00
|
|
|
metrics = require('./metrics')
|
|
|
|
|
|
|
|
if typeof obj[methodName] != 'function'
|
2017-03-16 10:02:19 +00:00
|
|
|
throw new Error("[Metrics] expected object property '#{methodName}' to be a function")
|
2017-03-15 15:06:54 +00:00
|
|
|
|
2018-11-27 10:46:54 +00:00
|
|
|
key = "#{prefix}.#{methodName}"
|
2018-11-27 10:01:33 +00:00
|
|
|
|
2018-11-27 10:46:54 +00:00
|
|
|
realMethod = obj[methodName]
|
2018-11-27 10:01:33 +00:00
|
|
|
|
2018-11-27 12:04:50 +00:00
|
|
|
splitPrefix = prefix.split(".")
|
|
|
|
startPrefix = splitPrefix[0]
|
|
|
|
|
|
|
|
if splitPrefix[1]?
|
|
|
|
modifedMethodName = "#{splitPrefix[1]}_#{methodName}"
|
|
|
|
else
|
|
|
|
modifedMethodName = methodName
|
2017-03-15 15:06:54 +00:00
|
|
|
obj[methodName] = (originalArgs...) ->
|
|
|
|
|
|
|
|
[firstArgs..., callback] = originalArgs
|
2017-03-20 16:17:22 +00:00
|
|
|
|
2017-03-15 15:06:54 +00:00
|
|
|
if !callback? || typeof callback != 'function'
|
2017-03-20 16:37:53 +00:00
|
|
|
if logger?
|
|
|
|
logger.log "[Metrics] expected wrapped method '#{methodName}' to be invoked with a callback"
|
|
|
|
return realMethod.apply this, originalArgs
|
2017-03-15 15:06:54 +00:00
|
|
|
|
2018-12-04 17:01:30 +00:00
|
|
|
timer = new metrics.Timer(startPrefix, 1, {method: modifedMethodName})
|
2017-03-15 15:06:54 +00:00
|
|
|
|
2017-03-15 16:07:36 +00:00
|
|
|
realMethod.call this, firstArgs..., (callbackArgs...) ->
|
2017-03-16 15:07:25 +00:00
|
|
|
elapsedTime = timer.done()
|
2017-03-20 16:54:40 +00:00
|
|
|
possibleError = callbackArgs[0]
|
2017-03-21 14:19:12 +00:00
|
|
|
if possibleError?
|
2018-12-04 17:01:30 +00:00
|
|
|
metrics.inc "#{startPrefix}_result", 1, {status:"failed", method: modifedMethodName}
|
2017-03-20 16:54:40 +00:00
|
|
|
else
|
2018-12-04 17:01:30 +00:00
|
|
|
metrics.inc "#{startPrefix}_result", 1, {status:"success", method: modifedMethodName}
|
2017-03-15 15:06:54 +00:00
|
|
|
if logger?
|
2017-03-17 14:20:13 +00:00
|
|
|
loggableArgs = {}
|
|
|
|
try
|
|
|
|
for arg, idx in firstArgs
|
|
|
|
if arg.toString().match(/^[0-9a-f]{24}$/)
|
|
|
|
loggableArgs["#{idx}"] = arg
|
|
|
|
logger.log {key, args: loggableArgs, elapsedTime}, "[Metrics] timed async method call"
|
2017-03-15 15:06:54 +00:00
|
|
|
callback.apply this, callbackArgs
|