Last active
October 5, 2018 09:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Class `MetricsMethodUtilsService` helps to manually call DropWizard metrics with custom class | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DemoController() { | |
MetricsMethodUtilsService metricsMethodUtilsService | |
def index() { | |
render metricsMethodUtilsService.start(getClass(), "index", { | |
"Hello World" | |
}) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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