介紹java
BTrace 是一個針對Java的安全的,動態的跟蹤工具。它經過動態替換字節碼,添加跟蹤代碼,來完成跟蹤任務。安全
1)無侵入(侵入小)工具
2)不修改應用任何數據測試
3)限制跟蹤功能spa
下載安裝code
1/下載 btrace-bin.zip包,解壓到btrace文件夾(unzip btrace-bin.zip -d btrace)ip
2/ 運行sh /btrace/bin/btraceget
實用例子io
DailyTest.java 待監控的測試類class
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))); } }