一、Btrace简介
BTrace可以动态的向目标应用程序的字节码注入追踪代码
用到的技术JavaComplierApi,JVMTI,Agent,Instrumentation+ASM
二、Btrace安装
1、下载
Btrace的Github地址
https://github.com/btraceio/btrace
进入Release Page

Linux版本btrace-bin-1.3.11.3.tgz
Window 版本 btrace-bin-1.3.11.3.zip
我这里下载的是window版本
2、配置环境变量
1) 新建BTRACE_HOME

2) 修改Path
新建环境变量BTRACE_HOME
添加Path: %BTRACE_HOME%\bin
3、测试
1) 创建接口
package com.example.monitor_tuning.chapter4;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/ch4")
public class Ch4Controller {
@RequestMapping("/arg1")
public String arg1(@RequestParam("name")String name){
return "hello," + name;
}
}
2) 测试接口

3) 创建Btrace脚本
加入Btrace测试
增加引用
<dependency> <groupId>com.sun.btrace</groupId> <artifactId>btrace-agent</artifactId> <version>1.3.11</version> <type>jar</type> <scope>system</scope> <systemPath>D:/Study/javaMonitor/btrace-bin-1.3.11.3/build/btrace-agent.jar</systemPath> </dependency> <dependency> <groupId>com.sun.btrace</groupId> <artifactId>btrace-boot</artifactId> <version>1.3.11</version> <type>jar</type> <scope>system</scope> <systemPath>D:/Study/javaMonitor/btrace-bin-1.3.11.3/build/btrace-boot.jar</systemPath> </dependency> <dependency> <groupId>com.sun.btrace</groupId> <artifactId>btrace-client</artifactId> <version>1.3.11</version> <type>jar</type> <scope>system</scope> <systemPath>D:/Study/javaMonitor/btrace-bin-1.3.11.3/build/btrace-client.jar</systemPath> </dependency>
然后
package com.example.monitor_tuning.chapter4;
import com.sun.btrace.AnyType;
import com.sun.btrace.BTraceUtils;
import com.sun.btrace.annotations.*;
/**
* 此Btrace脚本和要跟踪的代码不是放在同一个工程里的。这里演示方便,放在一起。
*/
@BTrace
public class PrintArgSimple {
/*要拦截哪个类,哪个方法,什么时候拦截*/
@OnMethod(
clazz = "com.example.monitor_tuning.chapter4.Ch4Controller",
method="arg1",
location = @Location(Kind.ENTRY)
)
/*ProbeClassName 方法类名; ProbeMethodName 方法名 ; AnyType[] 方法参数*/
public static void anyRead(@ProbeClassName String pcn, @ProbeMethodName String pmn, AnyType[] args)
{
BTraceUtils.printArray(args);
BTraceUtils.println(pcn + "," + pmn);
BTraceUtils.println();
}
}
将此文件移动到

4) 查看进程jps -l

5) 将脚本注入到进程 btrace 4584 PrintArgSimple.java。
然后访问接口http://localhost:8080/monitor_tuning/ch4/arg1?name=Jack

最终可以看到监控到了方法,参数等信息。
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!
浙公网安备 33010602011771号