Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- }
- /**
- * Wywołuje przekazany Closure wraz ze zwrotem dancyh z niego. Przed wykonanie i po rejestruje metryki wykonania
- * analogicnie do działania adnotacji @Timed, ale pozwala na przekazania dowolnego identyfikatora metryki
- *
- * @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()
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement