简体   繁体   中英

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 :

To debug issues, it is always a good idea to register an AgentBuilder.Listener with your agent. The instrumentation API in the JVM suppresses all exceptions that are thrown during an instrumentation and the listener allows you to catch those exceptions and to print them for example.

For such "around" instrumentation, I generally recommend using Advice as it does not make assumptions on class loader hierarchies which you need to address explicitly when using delegation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM