您的位置:首页 > 其它

BTrace使用方法之一

2012-01-17 23:24 169 查看
使用btrace可以在不改进代码,不影响当前线上运行的基础上进行运行时环境的跟踪,可以免去打日志,发部等繁琐的工作

使用Btrace可以从官网上下载相应二进制文件

下载地址为:http://kenai.com/projects/btrace/downloads

下载后解压,需要配置环境变量

将目录 btrace/bin 配置到自己的PATH环境变量中, 同进也可以将btrace/build配置到classpath当中去

LINUX下编辑/etc/profile文件,可将上述配置弄好,然后执行source /etc/profile可使用变量生效

配置完成后在终端执行 btrace 命令,若出现如下结果表明安装正确

Usage: btrace <options> <pid> <btrace source or .class file> <btrace arguments>

where possible options include:

-classpath <path> Specify where to find user class files and annotation processors

-cp <path> Specify where to find user class files and annotation processors

-I <path> Specify where to find include files

-p <port> Specify port to which the btrace agent listens for clients

尝试第一个BTrace应用

编写测试类 Case1 and CaseObject

import java.util.Random;
public class Case1{

public static void main(String[] args) throws Exception{
Random random=new Random();
CaseObject object=new CaseObject();
boolean result=true;
while(result){
result=object.execute(random.nextInt(1000));
Thread.sleep(1000);
}
}

}
class CaseObject{

private static int sleepTotalTime=0;

public boolean execute(int sleepTime) throws Exception{
System.out.println("sleep: "+sleepTime);
sleepTotalTime+=sleepTime;
Thread.sleep(sleepTime);
return true;
}

}
第二步,编写BTrace角本 TraceMethodArgsAndReturn.java

import static com.sun.btrace.BTraceUtils.*;
import com.sun.btrace.annotations.*;

@BTrace
public class TraceMethodArgsAndReturn{

@OnMethod(
clazz="CaseObject",
method="execute",
location=@Location(Kind.RETURN)
)
public static void traceExecute(@Self CaseObject instance,int sleepTime,@Return boolean result){
println("call CaseObject.execute");
println(strcat("sleepTime is:",str(sleepTime)));
println(strcat("sleepTotalTime is:",str(get(field("CaseObject","sleepTotalTime"),instance))));
println(strcat("return value is:",str(result)));
}
}
注意,在这里我们两个文件都放在同一个目录,同时需要将第一个java文件编译成class文件,即字节码

将Case1程序运行起来,他将是一个无限循环的程序,这样可以保证一直在运行,方便我们去捕获运行时的一些信息

下一步我们将用jps命令去查看case1进程的pid是多少, 假如我们获得的Case1的pid是4444

最后一步我们将执行btrace角本去获得相关信息, 执行命令如下

btrace <options> <pid> <btrace source or .class file> <btrace arguments>

在我们这个实例中就是:

btrace 4444 TraceMethodArgsAndReturn.java

执行完后你就可以看到效果了啦.........................
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: