I don't know if there is a way to get the timer context object, but I have another idea. You said this method is called not so often. Why not use DynamicFeature and print the execution time of the container?
Below I will show you how this can be implemented. I'm not sure if this works, I just coded it without any test, so please try it and change it if needed. If the ExecutionTimeFilter needs a split in two seperate classes due to the implemented interfaces, then change it accordingly.
Step 1: Create Filter
@Provider
public class ExecutionTimeFilter implements ContainerRequestFilter, ContainerResponseFilter {
public static final String EXECUTION_TIME_HEADER = "X-Execution-Time";
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
requestContext.getHeaders().add(EXECUTION_TIME_HEADER, ZonedDateTime.now().toString());
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
ZonedDateTime executionStartHeader = ZonedDateTime.parse(requestContext.getHeaderString(EXECUTION_TIME_HEADER));
Duration executionTime = Duration.between(executionStartHeader, ZonedDateTime.now());
//you can also print some url informations or whatever you need; check out the informations from both mehtod params
System.out.println("The execution time was:" + executionTime);
}
}
Step 2: Create DynamicFeature
@Provider
public class ExecutionTimeFeature implements DynamicFeature {
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
if (resourceInfo.getResourceMethod().getAnnotation(ExecutionTime.class) != null) {
context.register(ExecutionTimeFilter.class);
}
}
}
Step 3: Create Annotation
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExecutionTime {
}
Step 4: Annotate your resource
@GET
@ExecutionTime
public String getExcpensiveCalculation(@QueryParam("number") @DefaultValue("1") IntegerParam number) {
return getCalculation(number);
}
Step 5: Register Feature
environment.jersey().register(ExecutionTimeFeature.class);
References:Dropwizard Dynamic Feature with Filters