Unable to intercept method call via Byte Buddy agent

40 views Asked by At

I want to intercept a method call via byte buddy to do some logging. I already have compile-time byte code enhancement working, but am not having luck with setting up the same thing, but with an agent:

Interceptor:

public class LogInterceptor {
  @RuntimeType
  public static Object intercept(
      @Origin Method method,
      @SuperCall Callable<?> callable) throws Exception {
    LOGGER.info("intercepting: {}", method);
    System.out.println("intercepting: " + method);
    return callable.call();
  }
}

Agent:

void premain(String arguments, Instrumentation instrumentation) {
    final Method method = SomeClass.class.getDeclaredMethod("toString");

    ElementMatcher.Junction<MethodDescription> executeMethodDecription = ElementMatchers.isMethod()
              .and(ElementMatchers.named(method.getName()))
              .and(ElementMatchers.not(ElementMatchers.isAbstract()))
              .and(ElementMatchers.is(method));

    final AgentBuilder agentBuilder = new AgentBuilder.Default()
        .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION);
agentBuilder.type(ElementMatchers.is(method.getDeclaringClass()))
        .transform((builder, type, classLoader, module, other) ->
          builder.method(executeMethodDecription).intercept(MethodDelegation.to(LogInterceptor.class))).installOn(instrumentation);
      }

Cmdline:

java -javaagent:log-agent-shaded.jar -jar application.jar > .log 2>&1

When running the cmdline as show above, I have an additional log statement printing a warning that it is installing on the class and method I expect. However, at runtime, I don't see the log statement I am expecting.

In my plugin, I have essentially this:

builder.method(ElementMatchers.is(methodDescription)).intercept(MethodDelegation.to(LogInterceptor.class));

I am able to intercept the method if used at compile-time, but I also want to be able to do the same at runtime.

1

There are 1 answers

2
Rafael Winterhalter On

It seems like you are loading the class from your agent. In this case, you'd need to activate retransformation. Better though if you avoid the premature loading altogether and obly match by using strings.