btrace簡介:java
btrace是一種動態跟蹤分析一個運行中的Java應用程序的工具,它基於java的探針技術動態地向目標應用程序的字節碼注入追蹤代碼(字節碼追蹤),這些追蹤字節碼追蹤代碼使用Java語言表達,也就是BTrace的腳本git
btrace在github上的地址:
https://github.com/btraceio/btracegithub
編譯好的軟件包的下載地址:
https://github.com/btraceio/btrace/releases工具
如今(2017年二月)的最新版本是v1.3.9 咱們把btrace-bin-1.3.9.zip下載以後解壓到磁盤的某個位置而後配置BTRACE_HOME(好比,若是咱們將下載下來的文件解壓到D盤根目錄,就將BTRACE_HOME配置爲 D:\btrace-bin-1.3.9),而後將BTRACE_HOME文件夾下的bin目錄配置到path裏this
假設,咱們的目標代碼以下code
/* * Created with Intellij IDEA * USER: 焦一平 * Mail: jiaoyiping@gmail.com * Date: 2017/2/5 * Time: 21:24 * To change this template use File | Settings | Editor | File and Code Templates */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Demo { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("please input the first param:"); String p1 = bufferedReader.readLine(); System.out.println("please input the first param:"); String p2 = bufferedReader.readLine(); getResult(Integer.parseInt(p1), Integer.parseInt(p2)); System.out.println("press ENTER TO EXIT ..."); bufferedReader.readLine(); } public static int getResult(int param1, int param2) { return param1 * param2; } }
監控的代碼以下:blog
import com.sun.btrace.annotations.*; @BTrace(unsafe = true) public class BtraceTest { @OnMethod(clazz = "Demo", method = "getResult", location = @Location(Kind.RETURN)) public static void getParamAndResultByBtrace(int param1, int param2, @Return int result) { System.out.println("===========BTrace begin=================="); System.out.println("the first param:" + param1); System.out.println("the second param:" + param2); System.out.println("result: " + result); System.out.println("===========BTrace end===================="); } }
編譯並運行目標代碼(此時先不要輸入須要的參數,由於監控代碼還未植入),運行jps獲取執行目標代碼的進程id,咱們獲得pid爲9284
進程
cd到BtraceTest.java所在的文件夾,ip
執行: btrace 9284 BtraceTest.java
此時,監控代碼就被注入到了目標代碼中,咱們輸入目標代碼須要的兩個參數以後,會看到,參數和返回結果被輸出了出來:get