简体   繁体   English

ByteBuddy 代理打印方法经过的时间

[英]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:我正在使用 ByteBuddy 并创建了以下拦截器类:

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:这是我正在使用的 Java 代理类:

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.我运行了一个测试应用程序,其中包括以“BP”作为前缀命名的方法,并且未显示类 TimingInterceptor 中指示方法持续时间的消息。

Some ideas guys?一些想法家伙?

Example full code :示例完整代码

To debug issues, it is always a good idea to register an AgentBuilder.Listener with your agent.要调试问题,向您的代理注册一个AgentBuilder.Listener总是一个好主意。 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. JVM 中的检测 API 抑制检测期间抛出的所有异常,并且侦听器允许您捕获这些异常并打印它们。

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.对于这种“围绕”的工具,我通常建议使用Advice ,因为它不会对您在使用委托时需要明确解决的类加载器层次结构做出假设。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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