前提安装好了VisualVM,并且安装了插件BTrace(期间出现了一个小问题,那就是标签里面怎么找不到BTrace标签,后面经过实践在VisualVM的application里找到要调试的进程,然后通过右击那个进程即可找到BeTrace这个标签,来进行coding)
1、我这在esclipse里面的演示demo coding如下:
1 /** 2 * 3 */ 4 /** 5 * @author Administrator 6 * 7 */ 8 package com.lyq.demo; 9 10 import java.io.BufferedReader; 11 import java.io.IOException; 12 import java.io.InputStreamReader; 13 14 public class BTraceTest{ 15 16 public int add(int a, int b) { 17 return a+b; 18 } 19 20 public static void main(String[] argStrings) throws IOException{ 21 22 BTraceTest bTraceTest = new BTraceTest(); 23 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 24 25 for(int i=0; i<10; ++i){ 26 reader.readLine(); 27 int a = (int)Math.round(Math.random()*1000); 28 int b = (int)Math.round(Math.random()*1000); 29 System.out.println(bTraceTest.add(a, b)); 30 } 31 32 } 33 }
2、在VisualVM里想动态调试输出日志的代码如下:
1 /* BTrace Script Template */ 2 import com.sun.btrace.annotations.*; 3 import static com.sun.btrace.BTraceUtils.*; 4 5 @BTrace 6 public class TracingScript { 7 /* put your code here */ 8 @OnMethod( 9 clazz="com.lyq.demo.BTraceTest", 10 method="add", 11 location=@Location(Kind.RETURN) 12 ) 13 public static void func(@Self com.lyq.demo.BTraceTest instance, int a, int b, @Return int result) 14 { 15 println("调用堆栈:"); 16 jstack(); 17 println(strcat("方法参数A: ",str(a))); 18 println(strcat("方法参数B: ",str(b))); 19 println(strcat("方法结果: ",str(result))); 20 } 21 22 }
3、接下来编译通过后,在eclipse里调试,或者已经放到tomcat里运行的程序运行时,VisualVM里会对应的输出你要调试的代码的结果,如图示:
时间: 2024-12-31 03:40:30