vendredi 13 mai 2022

ByteBuddy Agent to print method elapsed time

I'm trying to measure the time for certains method of some specific classes. I'm using ByteBuddy and I created the following interceptor class:

public class TimingInterceptor {
    @RuntimeType
    public static Object intercept(@Origin Method method,
                                   @SuperCall Callable<?> callable) {
        long start = System.currentTimeMillis();
        try {
            return callable.call();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(method + " took " + (System.currentTimeMillis() - start));
        }
        return null;
    }
}

And this is the Java Agent Class I'm using:

public class TimerAgent {
    public static void premain(String arguments,
                               Instrumentation instrumentation) {

        new AgentBuilder.Default()
                .type(ElementMatchers.nameStartsWith("BP")) // This is because I used the prefix BP to name methods I need to measure
                .transform((builder, type, classLoader, module) ->
                        builder.method(ElementMatchers.any())
                                .intercept(MethodDelegation.to(TimingInterceptor.class))
                ).installOn(instrumentation);
    }
}

I ran a test application including methods named with "BP" as prefix, and the message in the class TimingInterceptor indicating the method duration is not shown.

Some ideas guys?

Example full code:





Aucun commentaire:

Enregistrer un commentaire