http://www.jianshu.com/p/26f19095d396 background
The production environment may have a variety of problems, but these problems are not caused by the program error, may be a logical error, it is necessary to obtain the program runtime data information, such as method parameters, return values to locate the problem, through the traditional way to increase logging is very cumbersome, and need to restart the server, It's a big price. Btrace came into being, can dynamically track Java running program, the tracking byte code injected into the running class, the running code intrusion is small, the impact on performance can be ignored.
Configuration and usage
Go to the official website to download btrace, configure the environment variable to execute the btrace command under any path.
Command format:
Btrace [-P <port>] [-CP <classpath>] <pid> <btrace-script>
PORT Specifies the service-side listener port number of the Btrace agent, which is used to listen for clients, which defaults to 2020, optional.
Classpath is used to specify the class loading path, such as the use of third-party jar packages such as Netty in your btrace code.
The PID represents the process number, which can be obtained through the JPS command.
Btrace-script is the Btrace script.
Here is a btrace command I used to test, you can refer to:
Btrace-p 2020-cp/home/mountain/softwores/tomcat8/lib/servlet-api.jar (JPS | grep Bootstrap | awk ' {print $} ')/home/mo Untain/test/btrace.java
Actual combat
Get method parameters and return values
Business code:
public String sayHello(String name, int age) { return "hello everyone";}
Btrace Code:
Import Com.sun.btrace.BTraceUtils;ImportStatic com.sun.btrace.btraceutils.*;Import com.sun.btrace.annotations.*; @BTrace public class btrace { @OnMethod (Clazz = " Com.jiuyan.message.controller.AdminController ", method = " SayHello ", Location = @Location (kind.return) //function returns when executed, if not filled, Executed at the beginning of the function) public static Span class= "Hljs-keyword" >void sayhello (String name, int age, @Return String result) {println ( "name:" + name); println ( "Age:" + age); println (result); }}
Call SayHello (' Mountain ', 1), the output should be:
1hello everyone
Strings can be matched in regular order to achieve the purpose of monitoring specific problems:
if(BTraceUtils.matches(".*345.*", str)) { println(str);}
Calculate how long the method runs to consume
Btrace Code:
Import Java.util.Date;Import Com.sun.btrace.BTraceUtils;ImportStatic com.sun.btrace.btraceutils.*;import com.sun.btrace.annotations.*; @BTrace public class btrace { @OnMethod (Clazz = " Com.jiuyan.message.controller.AdminController ", method = " SayHello ", Location = @Location (Kind.return)) public static void sayhello (@Duration long Duration) {//Unit is nanosecond, to be converted to milliseconds println (strcat (" duration (ms): ", str (Duration/1000000))); }}
Java application Debugging tool--btrace tutorial