Java应用调试利器——BTrace教程

http://www.jianshu.com/p/26f19095d396

背景

生产环境中可能出现各种问题,但是这些问题又不是程序error导致的,可能是逻辑性错误,这时候需要获取程序运行时的数据信息,如方法参数、返回值来定位问题,通过传统的增加日志记录的方式非常繁琐,而且需要重启server,代价很大。BTrace应运而生,可以动态地跟踪java运行程序,将跟踪字节码注入到运行类中,对运行代码侵入较小,对性能上的影响可以忽略不计。

配置及用法

  1. 去官网下载BTrace,配置环境变量以便在任何路径下能执行btrace命令。

  2. 命令格式:

    btrace [-p <port>] [-cp <classpath>] <pid> <btrace-script>

port指定BTrace agent的服务端监听端口号,用来监听clients,默认为2020,可选。
classpath用来指定类加载路径,比如你的BTrace代码里用到了netty等第三方jar包。
pid表示进程号,可通过jps命令获取。
btrace-script即为BTrace脚本。
下面是我用来测试的一条btrace命令,大家可以参考一下:

btrace -p 2020 -cp /home/mountain/Softwores/tomcat8/lib/servlet-api.jar (jps | grep Bootstrap | awk '{print $1}') /home/mountain/test/Btrace.java

实战

  1. 获取方法参数以及返回值

    业务代码:

    public String sayHello(String name, int age) {
       return "hello everyone";
    }

    BTrace代码:

    import com.sun.btrace.BTraceUtils;
    import static com.sun.btrace.BTraceUtils.*;
    import com.sun.btrace.annotations.*;
    
    @BTrace
    public class Btrace {
    
       @OnMethod(
           clazz = "com.jiuyan.message.controller.AdminController",
           method = "sayHello",
           location = @Location(Kind.RETURN)//函数返回的时候执行,如果不填,则在函数开始的时候执行
       )
       public static void sayHello(String name, int age, @Return String result) {
           println("name: " + name);
           println("age: " + age);
           println(result);
       }
    
    }

    调用sayHello('mountain', 1),输出应该是:

    name: mountain
    age: 1
    hello everyone

    可以对字符串进行正则匹配以达到监控特定问题的目的:

    if(BTraceUtils.matches(".*345.*", str)) {
        println(str);
    }
  2. 计算方法运行消耗的时间

    BTrace代码:

    import java.util.Date;
    
    import com.sun.btrace.BTraceUtils;
    import static com.sun.btrace.BTraceUtils.*;
    import com.sun.btrace.annotations.*;
    
    @BTrace
    public class Btrace {
    
       @OnMethod(
           clazz = "com.jiuyan.message.controller.AdminController",
           method = "sayHello",
           location = @Location(Kind.RETURN)
       )
       public static void sayHello(@Duration long duration) {//单位是纳秒,要转为毫秒
           println(strcat("duration(ms): ", str(duration / 1000000)));
       }
    
    }
原文地址:https://www.cnblogs.com/ThinkVenus/p/7275993.html