Advertisement
Guest User

Alternative for grails.plugin.dropwizard.metrics.timer@Timed

a guest
Oct 5th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 1.73 KB | None | 0 0
  1.  
  2. import com.codahale.metrics.MetricRegistry
  3. import com.codahale.metrics.Timer
  4. import groovy.transform.stc.ClosureParams
  5. import groovy.transform.stc.FirstParam
  6. import groovy.util.logging.Log4j
  7.  
  8. @Log4j
  9. class MetricsMethodUtilsService {
  10.     MetricRegistry metricRegistry
  11.  
  12.     private static LinkedHashMap<String, Timer> metricsContexts = []
  13.  
  14.     private Timer getTimerContext(Class clazz, String metricName) {
  15.         String contextKey = createContextKey(clazz, metricName)
  16.  
  17.         Timer context = metricsContexts.get(contextKey)
  18.  
  19.         if(!context) {
  20.             context = createContext(clazz, metricName)
  21.  
  22.             metricsContexts.put(contextKey, context)
  23.         }
  24.  
  25.         context
  26.     }
  27.  
  28.     private Timer createContext(Class clazz, String metricName) {
  29.        metricRegistry.timer(MetricRegistry.name(clazz, metricName))
  30.     }
  31.  
  32.     private String createContextKey(Class clazz, String metricName) {
  33.         clazz.name + "." + metricName
  34.     }
  35.  
  36.     /**
  37.      * Wywołuje przekazany Closure wraz ze zwrotem dancyh z niego. Przed wykonanie i po rejestruje metryki wykonania
  38.      * analogicnie do działania adnotacji @Timed, ale pozwala na przekazania dowolnego identyfikatora metryki
  39.      *
  40.      * @param clazz
  41.      * @param metricName
  42.      * @param body
  43.      * @return
  44.      */
  45.     def start(Class clazz, String metricName, @ClosureParams(FirstParam.FirstGenericType.class) Closure body) {
  46.         Timer.Context context = getTimerContext(clazz, metricName).time()
  47.  
  48.         if(!context) {
  49.             log.warn("Not found TimerContext for $clazz.$metricName")
  50.  
  51.             return body.call()
  52.         }
  53.  
  54.         try {
  55.             return body.call()
  56.         } finally {
  57.             context.stop()
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement