Btrace使用

介绍

 BTrace 是一个针对Java的安全的,动态的跟踪工具。它通过动态替换字节码,添加跟踪代码,来完成跟踪任务。

 1)无侵入(侵入小)

 2)不修改应用任何数据

 3)限制跟踪功能

下载安装

1/下载 btrace-bin.zip包,解压到btrace文件夹(unzip btrace-bin.zip -d btrace)

2/ 运行sh /btrace/bin/btrace

实用例子

Btrace使用_第1张图片

DailyTest.java 待监控的测试类

BtraceTestAdd.java、BtraceTestAttribute.java、BtraceTestExecuteTime.java 是Btrace脚本

public class DailyTest {
        private int count;

        public static void main(String[] args) {
                DailyTest test = new DailyTest();
                while (true) {
                        try {
                                System.out.println(test.sayHello("hello.."));
                                Thread.sleep(5000);
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                }
        }

        public String sayHello(String word) {
                return "dong-" + count++ + "-" + word;
        }
}

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

@BTrace
public class BtraceTestAdd {
   private static int count = 0;
   @OnMethod(
      clazz="DailyTest",
      method="sayHello",
      location=@Location(Kind.RETURN)
   )
   public static void traceExecute(String param,@Return String result){
        println(param);
        println(result);
   }
}

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

@BTrace
public class BtraceTestAttribute {
   private static Object count = 0;
   @OnMethod(
      clazz="DailyTest",
      method="sayHello",
      location=@Location(Kind.RETURN)
   )
   public static void traceExecute(@Self DailyTest dailyTest){
        count = get(field("DailyTest","count"),dailyTest);
        println(count);
   }
   @OnTimer(1000)
   public static void print(){
        println(strcat("count:",str(count)));
   }
}

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

@BTrace
public class BtraceTestExecuteTime {
   @TLS private static long startTime = 0;
   @OnMethod(
      clazz="DailyTest",
      method="sayHello"
   )
   public static void startExecute(){
        startTime = timeNanos();
   }

   @OnMethod(
      clazz="DailyTest",
      method="sayHello",
      location=@Location(Kind.RETURN)
   )
   public static void endExecute(@Duration long duration){
      long time = timeNanos()-startTime;
      println(strcat("execute time:",str(time)));
      println(strcat("duration:",str(duration)));
   }
}


你可能感兴趣的:(Btrace使用)