本文介紹了使用Byte Buddy的SLF4j記錄器的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我嘗試檢測名為ThreadPoolExecutor
的Java類,并希望使用slf4j記錄器獲取線程的詳細(xì)信息,但收到以下錯(cuò)誤
Exception in thread "pool-2-thread-2" Exception in thread "pool-2-thread-1" java.lang.NoClassDefFoundError: com/github/shehanperera/threadagent/MonitorInterceptor
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java)
at java.lang.Thread.run(Thread.java:748)java.lang.NoClassDefFoundError: com/github/shehanperera/threadagent/MonitorInterceptor
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java)
at java.lang.Thread.run(Thread.java:748)
這是我的代理
new AgentBuilder.Default()
.with(new AgentBuilder.InitializationStrategy.SelfInjection.Eager())
.ignore(ElementMatchers.none())
.type(ElementMatchers.nameContains("ThreadPoolExecutor"))
.transform((builder, type, classLoader, module) -> builder
.method(ElementMatchers.nameContains("run"))
.intercept(Advice.to(MonitorInterceptor.class))
).installOn(instrumentation);
和我的監(jiān)視器攔截器
public class MonitorInterceptor {
public static Logger logger = LoggerFactory.getLogger(MonitorInterceptor.class.getName());
@Advice.OnMethodEnter
static void enter(@Advice.Origin String method) throws Exception {
logger.info(String.valueOf(Arrays.asList(Thread.currentThread().getStackTrace())));
}}
記錄器以正常方式工作,沒有記錄器,它就能工作。當(dāng)我嘗試在Enter方法中使用記錄器時(shí),會(huì)出現(xiàn)錯(cuò)誤。
對(duì)此有何建議!
推薦答案
如果將類用作Advice
,則此類只是一個(gè)模板,而不是實(shí)際執(zhí)行的代碼。這意味著您不能引用對(duì)執(zhí)行方法不可見的字段,如類中的logger
字段。
因?yàn)槟跈z測JVM的一個(gè)類,所以這個(gè)類將被加載到引導(dǎo)路徑上,該路徑看不到您的類路徑,其中將加載SLF4j之類的類。如果要將類添加到引導(dǎo)路徑,則必須顯式執(zhí)行此操作。請(qǐng)查看Instrumentation::appendToBootstrapClassLoaderSearch
以執(zhí)行此操作。
這篇關(guān)于使用Byte Buddy的SLF4j記錄器的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,