BTrace 能夠動態地向目標應用程序的字節碼注入追蹤代碼,使用的技術有 JavaCompilerApi, JVMTI, Agent, Instrumentation+ASMjava
使用方法:JVisualVM中添加 BTrace 插件git
方法二:btrace <pid> <trace_script>github
monitor_tuning中新增包org.alanhou.monitor_tuning.chapter4web
安裝BTrace 要記得配置環境變量,以 Windows 爲例正則表達式
BTRACE_HOME=E:\tool\btrace-2.0.1-bin PTAH 加上 %BTRACE_HOME%\bin
安裝BTrace 要記得配置環境變量,以 Mac 爲例apache
# vi ~/.bash_profile BTRACE_HOME=/Applications/btrace PATH=$PATH:$BTRACE_HOME/bin export PATH # source ~/.bash_profile
pom.xml 中添加 btrace-agent, btrace-boot, btrace-client的依賴bash
訪問:http://localhost:12345/ch4/arg1?name=Javaapp
# 示例輸出 192:chapter4 alan$ btrace 2247 PrintArgSimple.java [Java, ] org.alanhou.monitor_tuning.chapter4.Ch4Controller,arg1
常見問題:Please set JAVA_HOME before running this script函數
# vi ~/.bash_profile export JAVA_HOME=$(/usr/libexec/java_home) # source ~/.bash_profile
攔截方法this
普通方法:@OnMethod( clazz=「」, method=「」),如上例(PrintArgSimple.java)
構造函數:@OnMethod( clazz=「」, method=「<init> 「)(PrintContructor.java)
192:chapter4 alan$ btrace 3682 PrintConstructor.java org.alanhou.monitor_tuning.chapter2.User,<init> [1, Java, ]
攔截同名函數:用參數區分(PrintSame.java)
以下例中雖然方法名相同,但分別有一個和兩個參數
@RequestMapping("/same1") public String same(@RequestParam("name")String name) { // 訪問地址: http://localhost:12345/ch4/same1?name=Java return "Hello, "+name; } @RequestMapping("/same2") public String same(@RequestParam("name")String name, @RequestParam("id")int id) { // 訪問地址: http://localhost:12345/ch4/same2?name=Java&id=1 return "Hello, "+name+", "+id; }
攔截時機
Kind.ENTRY: 入口,默認值(上述例子均爲這種狀況)
Kind.RETURN: 返回(PrintReturn.java)
192:chapter4 alan$ btrace 3981 PrintReturn.java org.alanhou.monitor_tuning.chapter4.Ch4Controller,arg1,Hello, Java
Kind.THROW: 異常(PrintOnThrow.java)
192:chapter4 alan$ btrace 4041 PrintOnThrow.java java.lang.ClassNotFoundException: org.apache.catalina.webresources.WarResourceSet ... java.lang.ArithmeticException: / by zero org.alanhou.monitor_tuning.chapter4.Ch4Controller.exception(Ch4Controller.java:40) ...
Kind.Line: 行(PrintLine.java)
# 打印指定行號是否執行 192:chapter4 alan$ btrace 4149 PrintLine.java org.alanhou.monitor_tuning.chapter4.Ch4Controller,exception,39
攔截 this、入參、返回值
this:@self
入參:能夠用 AnyType,也能夠用真實類型,同名的用真實的
返回:@Return
獲取對象的值
簡單類型:直接獲取
複雜類型:反射,類名+屬性名(PrintArgComplex.java)
192:chapter4 alan$ btrace -cp "/Users/alan/Desktop/demo/java-code/monitor_tuning/target/classes" 4337 PrintArgComplex.java {id=1, name=Java, } Java org.alanhou.monitor_tuning.chapter4.Ch4Controller,arg2
攔截函數中還能夠使用正則表達式,如method=」/.*/」匹配指定類下的全部方法(PrintRegex.java)
打印環境變量(PrintJinfo.java)