最近在看深入理解Java虛擬機,裏面講解了如何通過VisualVM爲線上程序打印日誌。我們打開VisualVM,安裝BTrace動態日誌跟蹤插件。以下是應用程序演示代碼:產生兩個1000以內的隨機整數,輸出這兩個數字相加的結果。
public class BTraceTest {
public int add(int a,int b){
return a+b;
}
public static void main(String[] args) throws IOException {
BTraceTest bt = new BTraceTest();
BufferedReader reader = new BufferedReader(new InputStreamReader((System.in)));
for(int i = 0; i < 10; i++){
reader.readLine();
int a = (int) Math.round(Math.random() * 1000);
int b = (int) Math.round(Math.random() * 1000);
System.out.println(bt.add(a,b));
}
}
}
啓動程序後,VisualVM會顯示我們的應用程序,如下圖
在應用程序上右擊,出現“Trace Application...”菜單,點擊打開。出現以下界面:
在上面界面輸入調試代碼,如下:
@BTrace
public class TracingScript {
/* put your code here */
@OnMethod(
clazz="BTraceTest",
method="add",
location=@Location(Kind.RETURN)
)
public static void func(@Self BTraceTest instance,int a,int b,@Return int result){
println("調用堆棧");
jstack();
println(strcat("方法參數A:",str(a)));
println(strcat("方法參數B:",str(b)));
println(strcat("方法結果:",str(result)));
}
}
點擊start按鈕,在Output面板中出現BTrace up&running代表啓動成功。
此時,回到我們的應用程序,在控制檯輸入內容,在VisualVM的Outpt在打印參數和結果。
如下圖:
到此結束。
哈哈,以前線上出現問題只能改動代碼加打印日誌,再重啓。收穫一個強大的功能。