一、Btrace简介

BTrace可以动态的向目标应用程序的字节码注入追踪代码

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

用到的技术JavaComplierApi,JVMTI,Agent,Instrumentation+ASM

 

二、Btrace安装

1、下载

Btrace的Github地址

https://github.com/btraceio/btrace

 

进入Release Page

Btrace介绍 随笔 第1张

Linux版本btrace-bin-1.3.11.3.tgz

Window 版本 btrace-bin-1.3.11.3.zip

 我这里下载的是window版本

 

2、配置环境变量

1) 新建BTRACE_HOME

Btrace介绍 随笔 第2张

 

 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) 测试接口 

Btrace介绍 随笔 第3张

 

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();
    }
}

  

将此文件移动到

Btrace介绍 随笔 第4张

 

  

 

4) 查看进程jps -l

Btrace介绍 随笔 第5张

 

 5) 将脚本注入到进程 btrace 4584 PrintArgSimple.java。

然后访问接口http://localhost:8080/monitor_tuning/ch4/arg1?name=Jack

Btrace介绍 随笔 第6张

 最终可以看到监控到了方法,参数等信息。

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄