BTrace本身也是可以独立运行的程序,作用是在不停止目标程序运行的前提下,通过HotSpot虚拟机的HotSwap技术动态插入原本不存在的调试代码。
比如遇到了我们的程序出问题,而又没有足够的打印语句时,我们一般的方法是不得不停掉服务,然后修改代码,增加打印语句,重新编译重新运行来解决,效率很低。
但有了BTrace,我们需要做的就很简单了,举例说明:
比如环境上运行着一个简单程序:
- package com.huawei.main;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- public class Main
- {
- public static void main(String[] args) throws Exception
- {
- Main test = new Main();
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
- for (int i = 0; i < 10; i++)
- {
- reader.readLine();
- int a = (int) Math.round(Math.random() * 1000);
- int b = (int) Math.round(Math.random() * 1000);
- System.out.println(test.add(a, b));
- }
- }
- public int add(int a, int b)
- {
- return a + b;
- }
- }
package com.huawei.main;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main
{
public static void main(String[] args) throws Exception
{
Main test = new Main();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 10; i++)
{
reader.readLine();
int a = (int) Math.round(Math.random() * 1000);
int b = (int) Math.round(Math.random() * 1000);
System.out.println(test.add(a, b));
}
}
public int add(int a, int b)
{
return a + b;
}
}
该程序从控制台中获取一个输入,然后生成两个随机数,相加后将结果打印出来
对于add方法没有日志打印,如果想在不改变程序的前提下知道程序运行时add函数的入参和返回值,我们可以:
1. 在环境上解压BTrace工具包
比如解压到:/opt/eucalyptus/test/目录下
2. 编写BTrace脚本,对于脚本还是需要时间学习和实践的。如下TraceScript.java(注意在Linux下,这个文件应该是ANSI格式,否则会报illegal character: \65279的异常):
- import com.sun.btrace.annotations.*;
- import static com.sun.btrace.BTraceUtils.*;
- @BTrace
- public class TraceScript
- {
- @OnMethod(clazz="com.huawei.main.Main", method="add", location=@Location(Kind.RETURN))
- public static void func(int a, int b, @Return int result)
- {
- jstack();
- println(strcat("para A: ", str(a)));
- println(strcat("para B: ", str(b)));
- println(strcat("result: ", str(result)));
- }
- }
import com.sun.btrace.annotations.*;
import static com.sun.btrace.BTraceUtils.*;
@BTrace
public class TraceScript
{
@OnMethod(clazz="com.huawei.main.Main", method="add", location=@Location(Kind.RETURN))
public static void func(int a, int b, @Return int result)
{
jstack();
println(strcat("para A: ", str(a)));
println(strcat("para B: ", str(b)));
println(strcat("result: ", str(result)));
}
}
转载于:https://blog.51cto.com/ajiao13/1141803