Skip to content

Instantly share code, notes, and snippets.

@michmzr
Last active October 5, 2018 09:12
Show Gist options
  • Save michmzr/1e03534bc5fb6df89065f6964acf9c71 to your computer and use it in GitHub Desktop.
Save michmzr/1e03534bc5fb6df89065f6964acf9c71 to your computer and use it in GitHub Desktop.
Manual call alternative for grails.plugin.dropwizard.metrics.timers.@timed for Grails 3
Class `MetricsMethodUtilsService` helps to manually call DropWizard metrics with custom class
class DemoController() {
MetricsMethodUtilsService metricsMethodUtilsService
def index() {
render metricsMethodUtilsService.start(getClass(), "index", {
"Hello World"
})
}
}
import com.codahale.metrics.MetricRegistry
import com.codahale.metrics.Timer
import groovy.transform.stc.ClosureParams
import groovy.transform.stc.FirstParam
import groovy.util.logging.Log4j
@Log4j
class MetricsMethodUtilsService {
MetricRegistry metricRegistry
private static LinkedHashMap<String, Timer> metricsContexts = []
private Timer getTimerContext(Class clazz, String metricName) {
String contextKey = createContextKey(clazz, metricName)
Timer context = metricsContexts.get(contextKey)
if(!context) {
context = createContext(clazz, metricName)
metricsContexts.put(contextKey, context)
}
context
}
private Timer createContext(Class clazz, String metricName) {
metricRegistry.timer(MetricRegistry.name(clazz, metricName))
}
private String createContextKey(Class clazz, String metricName) {
clazz.name + "." + metricName
}
/**
* Call a passes Closure function. Function returns a closure response
*
* @param clazz
* @param metricName
* @param body
* @return
*/
def start(Class clazz, String metricName, @ClosureParams(FirstParam.FirstGenericType.class) Closure body) {
Timer.Context context = getTimerContext(clazz, metricName).time()
if(!context) {
log.warn("Not found TimerContext for $clazz.$metricName")
return body.call()
}
try {
return body.call()
} finally {
context.stop()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment