btrace 官网地址:https://kenai.com/projects/btrace
实现原理参考:http://www.ibm.com/developerworks/cn/java/j-lo-instrumentation/
1.首先使用VisualVM 下载btrace插件并安装完成。
2.在Eclipse中写个测试类如下:
package com.lss.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BTraceTest { public int add(int a, int b) { return a + b; } public void run(){ int a = (int) (Math.random() * 1000); int b = (int) (Math.random() * 1000); System.out.println(add(a, b)); } public static void main(String[] args) throws IOException { BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); BTraceTest bTraceTest=new BTraceTest(); bReader.readLine(); for (int i = 0; i < 10; i++) { bTraceTest.run(); } } }运行Main函数,阻塞等待控制台输入。
3. 在VisualVM中选择该监控服务右键点击trace application.
在TracingScript类中输入以下代码
/* BTrace Script Template */
import com.sun.btrace.annotations.*;
import static com.sun.btrace.BTraceUtils.*;
@BTrace
public class TracingScript {
/* put your code here */
@OnMethod(
clazz="com.lss.test.BTraceTest",
method="add",
location=@Location(Kind.RETURN)
)
public static void func(@Self com.lss.test.BTraceTest instance ,int a,int b,@Return int result){
println("调用堆栈");
jstack();
println(strcat("方法参数A:",str(a)));
println(strcat("方法参数B:",str(b)));
println(strcat("方法结果:",str(result)));
}
}
点击开始,控制台输出以下表示编译通过:
** Compiling the BTrace script ...
*** Compiled
** Instrumenting 1 classes ...
*** Done
** BTrace up&running
*** Done
** BTrace up&running
4.回到Eclipse 在控制台回车,让程序继续执行,完成后回到VisualVM 则看到控制台输出如下信息。