Detailed explanation of BTrace for Java online troubleshooting
What is BTrace
BTrace is a killer tool for checking and solving online problems. BTrace can obtain all the information during the execution of the program by writing scripts, and, please note, No need to restart the service, yes, no need to restart the service. After writing the script, you can execute it directly with the command without touching the original program code.
Principle
Installation and configuration
##
export JAVA_HOME=/home/fengzheng/soft/jdk1.8.0_111 export JRE_HOME=${JAVA_HOME}/jre export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib export PATH=${JAVA_HOME}/bin:$PATH export BTRACE_HOME=/home/fengzheng/soft/btrace export PATH=$PATH:$BTRACE_HOME/bin
Then execute the command
Simple test casebtrace The simplest syntax is
package kite.lab.utils; /** * NumberUtil * * @author fengzheng * @date 2017/2/15 */ public class NumberUtil { public int sum(){ int result = 0; for(int i = 0; i< 100; i++){ result += i * i; } return result; } public static void main(String[] args){ while (true) { Thread.currentThread().setName("计算"); NumberUtil util = new NumberUtil(); int result = util.sum(); System.out.println(result); try { Thread.sleep(5000); }catch (InterruptedException e){ } } } }
By the way, the process of compiling and running Java from the command line:
2. After executing the above program, you can use the
jps command to check the pid (generally, which account is used to start the program will depend on which account is used to execute jps, except for the root account). Execute the jps command to see the following results:
root@ubuntu:/home/fengzheng/codes/btrace# jps 10906 Jps 10860 NumberUtil
package kite; import com.sun.btrace.annotations.*; import static com.sun.btrace.BTraceUtils.Strings.strcat; import static com.sun.btrace.BTraceUtils.jstack; import static com.sun.btrace.BTraceUtils.println; import static com.sun.btrace.BTraceUtils.str; /** * NumberUtilBTrace * * @author fengzheng * @date 2017/6/20 */ @BTrace public class NumberUtilBTrace { @OnMethod( clazz="kite.lab.utils.NumberUtil", method="sum", location=@Location(Kind.RETURN) ) public static void func(@Return int result) { println("trace: ======================="); println(strcat("result:", str(result))); jstack(); } }
5. Preparation Compilation: You can use the precompilation command to check the correctness of the script before execution. The precompilation command is btracec, which is a javac-like command, btracec NumberUtilBTrace.java
# #6. Call the command line to execute, btrace 10860 NumberUtilBTrace.java, (if you want to save it to a local file, you can use the redirection command btrace 10860 NumberUtilBTrace.java > mylog.log). The printed information is as follows
trace: ======================= result:328350 kite.lab.utils.NumberUtil.sum(NumberUtil.java:16) kite.lab.utils.NumberUtil.main(NumberUtil.java:27)
7.
Press ctrl + c, the exit prompt will be given, then press 1 to exitUse Scenes
比如哪些方法执行太慢,例如监控执行时间超过1s的方法
查看哪些方法调用了 System.gc() ,调用栈是怎样的
查看方法参数或对象属性
哪些方法发生了异常
多说一点,为了更好解决问题,最好还要配合事前准备和进行中监控,事前准备就是埋点嘛,在一些可能出现问题的方法中进行日志输出,进行中监控就是利用一些实时监控工具,例如 VisualVM 、jmc 这些带界面的工具或者 jdk 提供的命令行工具等,再高级一点的就是利用 Graphite 这样的Metrics 工具配合 web 界面展示出来。
使用限制
BTrace class不能新建类, 新建数组, 抛异常, 捕获异常,
不能调用实例方法以及静态方法(com.sun.btrace.BTraceUtils除外)
不能将目标程序和对象赋值给BTrace的实例和静态field
不能定义外部, 内部, 匿名, 本地类
不能有同步块和方法
不能有循环
不能实现接口, 不能扩展类
不能使用assert语句, 不能使用class字面值
拦截方法定义
如何定位
1. 精准定位
直接定位到一个类下的一个方法,上面测试用的例子就是
2. 正则表达式定位
正则表达式在两个"/" 之间,例如下面的例子,监控 javax.swing 包下的所有方法,注意正式环境中,范围尽可能小一点,太大了性能会有影响。
@OnMethod(clazz="/javax\\.swing\\..*/", method="/.*/") public static void swingMethods( @ProbeClassName String probeClass, @ProbeMethodName String probeMethod) { print("entered " + probeClass + "." + probeMethod); }
通过在拦截函数的定义里注入@ProbeClassName String probeClass, @ProbeMethodName String probeMethod 参数,告诉脚本实际匹配到的类和方法名。
3. 按接口或继承类定位
@OnMethod(clazz="+com.kite.base", method="doSome")
4. 按注解定位
在前面加上 @ 即可,例如@OnMethod(clazz="@javax.jws.WebService", method="@javax.jws.WebMethod")
拦截时机
拦截时机由 location 决定,当然也可为同一个定位加入多个拦截时机,即可以在进入方法时拦截、方法返回时拦截、抛出异常时拦截
1. Kind.Entry与Kind.Return
2. Kind.Error, Kind.Throw和 Kind.Catch
表示异常被 throw 、异常被捕获还有异常发生但是没有被捕获的情况,在拦截函数的参数定义里注入一个Throwable的参数,代表异常
@OnMethod(clazz = "com.kite.demo", location = @Location(value = Kind.LINE, line = 20)) public static void onBind() { println("执行到第20行"); }
@OnMethod(clazz = "java.net.ServerSocket", method = "bind", location =@Location(Kind.ERROR)) public static void onBind(Throwable exception, @Duration long duration){ }
3. Kind.Call 和 Kind.Line
Kind.Call 表示被监控的方法调用了哪些其他方法,例如:
@OnMethod(clazz = "com.kite", method = "login", location = @Location(value = Kind.CALL, clazz = "/.*/", method = "/.*/", where = Where.AFTER)) public static void onBind(@Self Object self, @TargetInstance Object instance, @TargetMethodOrField String method, @Duration long duration){ println(strcat("self: ", str(self))); println(strcat("instance: ", str(instance))); println(strcat("method: ", str(method))); println(strcat("duration(ms): ", str(duration / 1000000))); }
Kind.Line 监测类是否执行到了设置的行数,例如:
@OnMethod(clazz = "com.kite.demo", location = @Location(value = Kind.LINE, line = 20)) public static void onBind() { println("执行到第20行"); }
几个例子
@OnMethod(clazz = "java.lang.System", method = "gc") public static void onSystemGC() { println("entered System.gc()"); jstack(); }
@OnMethod(clazz = "/com\\.kite\\.controller\\..*/",method = "/.*/",location = @Location(Kind.RETURN)) public static void slowQuery(@ProbeClassName String pcn,@ProbeMethodName String probeMethod, @Duration long duration){ if(duration > 1000000 * 100){ println(strcat("类:", pcn)); println(strcat("方法:", probeMethod)); println(strcat("时长:", str(duration / 1000000))); } }
注意问题
The above is the detailed content of Detailed explanation of BTrace for Java online troubleshooting. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
