欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Arthas在线java进程诊断工具在线调试神器详解

程序员文章站 2022-03-02 21:18:44
`arthas` 是 alibaba 开源的java诊断工具,深受开发者喜爱。当你遇到以下类似问题而束手无策时,`arthas`可以帮助你解决:1. 这个类从哪个 jar 包加载的?为什么会报各种类相...

`arthas` 是 alibaba 开源的java诊断工具,深受开发者喜爱。

当你遇到以下类似问题而束手无策时,`arthas`可以帮助你解决:

1. 这个类从哪个 jar 包加载的?为什么会报各种类相关的 exception?

2. 我改的代码为什么没有执行到?难道是我没 commit?分支搞错了?

3. 遇到问题无法在线上 debug,难道只能通过加日志再重新发布吗?

4. 线上遇到某个用户的数据处理有问题,但线上同样无法 debug,线下无法重现!

5. 是否有一个全局视角来查看系统的运行状况?

6. 有什么办法可以监控到jvm的实时运行状态?

7. 怎么快速定位应用的热点,生成火焰图?

8. 怎样直接从jvm内查找某个类的实例?

`arthas`支持jdk 6+,支持linux/mac/windows,采用命令行交互模式,同时提供丰富的 `tab` 自动补全功能,进一步方便进行问题的定位和诊断。

tag: java 诊断 堆栈 在线调试 耗时 死锁 arthas 阿里巴巴

arthas (阿尔萨斯

Arthas在线java进程诊断工具在线调试神器详解

arthas 是 alibaba 开源的java诊断工具,深受开发者喜爱。

官网文档:https://arthas.aliyun.com/doc/

当你遇到以下类似问题而束手无策时,arthas可以帮助你解决:

这个类从哪个 jar 包加载的?为什么会报各种类相关的 exception?我改的代码为什么没有执行到?难道是我没 commit?分支搞错了?遇到问题无法在线上 debug,难道只能通过加日志再重新发布吗?线上遇到某个用户的数据处理有问题,但线上同样无法 debug,线下无法重现!是否有一个全局视角来查看系统的运行状况?有什么办法可以监控到jvm的实时运行状态?怎么快速定位应用的热点,生成火焰图?怎样直接从jvm内查找某个类的实例?

arthas支持jdk 6+,支持linux/mac/windows,采用命令行交互模式,同时提供丰富的 tab 自动补全功能,进一步方便进行问题的定位和诊断。

安装

快速安装

1.1.1 使用arthas-boot(推荐)

下载arthas-boot.jar,然后用java -jar的方式启动:

curl -o https://arthas.aliyun.com/arthas-boot.jar
java -jar arthas-boot.jar

打印帮助信息:

java -jar arthas-boot.jar -h

如果下载速度比较慢,可以使用aliyun的镜像:

java -jar arthas-boot.jar --repo-mirror aliyun --use-http

使用as.sh方式安装

arthas 支持在 linux/unix/mac 等平台上一键安装,请复制以下内容,并粘贴到命令行中,敲 回车 执行即可:

curl -l https://arthas.aliyun.com/install.sh | sh

上述命令会下载启动脚本文件 as.sh 到当前目录,你可以放在任何地方或将其加入到 $path 中。

直接在shell下面执行./as.sh,就会进入交互界面。

也可以执行./as.sh -h来获取更多参数信息。

全量安装 (线上环境无外网访问权限)

# java -jar arthas-boot.jar
[info] arthas-boot version: 3.5.3
[info] found existing java process, please choose one and input the serial number of the process, eg : 1. then hit enter.
* [1]: 24438 org.elasticsearch.bootstrap.elasticsearch
1
[error] can not read arthas version from: https://arthas.aliyun.com/api/latest_version
[error] can not find arthas under local: /root/.arthas/lib and remote repo mirror: aliyun
[error] unable to download arthas from remote server, please download the full package according to wiki: https://github.com/alibaba/arthas

当使用快速安装方式在线上环境进行连接java服务的时候,很有可能因为线上环境无外部网络访问权限,导致arthas无法获取 arthas-core 等jar包,无法运行。

这时候就需要全量安装arthas包。

安装方法 : ( 包大小13mb )

#### 获取 arthas 全量包
curl -lo arthas-packaging-latest-bin.zip  'https://arthas.aliyun.com/download/latest_version?mirror=aliyun'
unzip -d arthas-latest-bin arthas-packaging-latest-bin.zip

#### 开始运行
java -jar ahthas-boot.jar
[info] arthas-boot version: 3.5.4
[info] found existing java process, please choose one and input the serial number of the process, eg : 1. then hit enter.
* [1]: 27878 /data/tsf/tsf-oss/tsf-ratelimit/tsf-ratelimit-1.29.1/lib/tsf-ratelimit-1.29.1.jar
1
[info] arthas home: /root
[info] try to attach process 27878
[info] attach process 27878 success.
[info] arthas-client connect 127.0.0.1 3658
  ,---.  ,------. ,--------.,--.  ,--.  ,---.   ,---.  
 /  o  \ |  .--. ''--.  .--'|  '--'  | /  o  \ '   .-' 
|  .-.  ||  '--'.'   |  |   |  .--.  ||  .-.  |`.  `-. 
|  | |  ||  |\  \    |  |   |  |  |  ||  | |  |.-'    |
`--' `--'`--' '--'   `--'   `--'  `--'`--' `--'`-----' 
                                                       

wiki       https://arthas.aliyun.com/doc
tutorials  https://arthas.aliyun.com/doc/arthas-tutorials.html
version    3.5.4
main_class
pid        27878
time       2021-09-07 19:31:47

通过 rpm/deb 来安装

这部分见官方文档.

快速入门

arthas 需要使用到 jps 命令,所以要保证 openjdk-devel 包已经安装。

jps || yum -y install java-1.8.0-openjdk-devel

运行 arthas:

# java -jar arthas-boot.jar
[info] arthas-boot version: 3.5.3
[info] process 5201 already using port 3658
[info] process 5201 already using port 8563
[info] found existing java process, please choose one and input the serial number of the process, eg : 1. then hit enter.
* [1]: 5201 cloud-access-auth-1.18.1.jar
  [2]: 14419 tsf-stack-base-1.0.0.jar
  [3]: 27862 cloud-access-gateway-1.18.1.jar
  [4]: 6550 tsfmanager-operation-1.29.1.jar

提示1:当 arthas 给出的进程列表不能确定进程信息的时候,我们可以通过在命令行输入jps -lmv 查看详细的 java 进程信息,来确定我们要查看的 java 进程号。

提示2:当提示如下信息时:

arthas script version: 3.0.4
calculating attach execution time...
attaching to 24110 using version 3.0.4...
start arthas failed, exception stack trace:
java.lang.internalerror: instrument library is missing in target vm
 at sun.tools.attach.hotspotvirtualmachine.loadagent(hotspotvirtualmachine.java:105)
 at com.taobao.arthas.core.arthas.attachagent(arthas.java:84)
 at com.taobao.arthas.core.arthas.<init>(arthas.java:25)
 at com.taobao.arthas.core.arthas.main(arthas.java:96)
caused by: com.sun.tools.attach.agentloadexception: failed to load agent library
 at sun.tools.attach.linuxvirtualmachine.execute(linuxvirtualmachine.java:224)
 at sun.tools.attach.hotspotvirtualmachine.loadagentlibrary(hotspotvirtualmachine.java:58)
 at sun.tools.attach.hotspotvirtualmachine.loadagentlibrary(hotspotvirtualmachine.java:79)
 at sun.tools.attach.hotspotvirtualmachine.loadagent(hotspotvirtualmachine.java:103)
 ... 3 more
attach to target jvm (24110) failed, check /root/logs/arthas/arthas.log or stderr of target jvm for any exceptions.

我们需要重新启动一下该进程,然后再运行 arthas ,连接到后台 java 进程即可。

下面的 java 进程编号即当前主机已经运行的 java 服务,输入编号即可进入 arthas 的交互式界面。

[info] found existing java process, please choose one and input the serial number of the process, eg : 1. then hit enter.
* [1]: 5201 cloud-access-auth-1.18.1.jar
  [2]: 14419 tsf-stack-base-1.0.0.jar
  [3]: 27862 cloud-access-gateway-1.18.1.jar
  [4]: 6550 tsfmanager-operation-1.29.1.jar
1
[info] local lastest version: 3.5.3, remote lastest version: 3.5.4, try to download from remote.
[info] start download arthas from remote server: https://arthas.aliyun.com/download/3.5.4?mirror=aliyun
[info] download arthas success.
[info] arthas home: /root/.arthas/lib/3.5.4/arthas
[info] the target process already listen port 3658, skip attach.
[info] arthas-client connect 127.0.0.1 3658
  ,---.  ,------. ,--------.,--.  ,--.  ,---.   ,---.  
 /  o  \ |  .--. ''--.  .--'|  '--'  | /  o  \ '   .-' 
|  .-.  ||  '--'.'   |  |   |  .--.  ||  .-.  |`.  `-. 
|  | |  ||  |\  \    |  |   |  |  |  ||  | |  |.-'    |
`--' `--'`--' '--'   `--'   `--'  `--'`--' `--'`-----' 
                                                       

wiki       https://arthas.aliyun.com/doc
tutorials  https://arthas.aliyun.com/doc/arthas-tutorials.html
version    3.5.3
main_class
pid        5201
time       2021-09-03 09:55:42

[arthas@5201]$

当出现上述彩条 arthas 字符提示的时候,就表示已经正常连接到指定的 java 进程,随即进入到下面的 arthas@pid 命令提示符。

功能使用

dashboard 指令 -- 总览jvm信息

在 arthas 命令提示符下键入dashboard 回车,会展示当前进程的信息,按q 退出。
Arthas在线java进程诊断工具在线调试神器详解

dashboard 会实时输出该java进程的jvm信息,包括线程、进程、内存、堆栈、以及当前系统运行时信息。

[arthas@5201]$ dashboard -h
 usage:       
   dashboard [-h] [-i <value>] [-n <value>]

 summary:  
   overview of target jvm's thread, memory, gc, vm, tomcat info.
   
 examples:  
   dashboard
   dashboard -n 10
   dashboard -i 2000
           
 wiki:           
   https://arthas.aliyun.com/doc/dashboard

 options:          
 -h, --help                                this help
 -i, --interval <value>                    the interval (in ms) between two executions, default is 5000 ms.
 -n, --number-of-execution <value>         the number of times this command will be executed.

help 指令

该指令用以列出所有 arthas 交互式界面支持的 子命令 列表。

[arthas@5201]$ help
 name         description
 help         display arthas help
 auth         authenticates the current session
 keymap       display all the available keymap for the specified connection.
 sc           search all the classes loaded by jvm
 sm           search the method of classes loaded by jvm
 classloader  show classloader info
 jad          decompile class
 getstatic    show the static field of a class
 monitor      monitor method execution statistics, e.g. total/success/failure count, average rt, fail rate, etc.
 stack        display the stack trace for the specified class and method
 thread       display thread info, thread stack
 trace        trace the execution time of specified method invocation.
 watch        display the input/output parameter, return object, and thrown exception of specified method invocation
 tt           time tunnel
 jvm          display the target jvm information
 perfcounter  display the perf counter information.
 ognl         execute ognl expression.
 mc           memory compiler, compiles java files into bytecode and class files in memory.
 redefine     redefine classes. @see instrumentation#redefineclasses(classdefinition...)
 retransform  retransform classes. @see instrumentation#retransformclasses(class...)
 dashboard    overview of target jvm's thread, memory, gc, vm, tomcat info.
 dump         dump class byte array from jvm
 heapdump     heap dump
 options      view and change various arthas options
 cls          clear the screen
 reset        reset all the enhanced classes
 version      display arthas version
 session      display current session information
 sysprop      display, and change the system properties.
 sysenv       display the system env.
 vmoption     display, and update the vm diagnostic options.
 logger       print logger info, and update the logger level
 history      display command history
 cat          concatenate and print files
 base64       encode and decode using base64 representation
 echo         write arguments to the standard output
 pwd          return working directory name
 mbean        display the mbean information
 grep         grep command for pipes.
 tee          tee command for pipes.
 profiler     async profiler. https://github.com/jvm-profiling-tools/async-profiler
 vmtool       jvm tool
 stop         stop/shutdown arthas server and exit the console.

每个子命令,都可以跟上 -h 来进一步获取帮助用法信息。

thread 指令

[arthas@5201]$ thread -h
 usage:   
   thread [--all] [-h] [-b] [--lockedmonitors] [--lockedsynchronizers] [-i <value>] [--state <value>] [-n <value>] [id]

 summary:     
   display thread info, thread stack
                                    
 examples: 
   thread
   thread 51
   thread -n -1
   thread -n 5
   thread -b
   thread -i 2000
   thread --state blocked
   
 wiki:                             
   https://arthas.aliyun.com/doc/thread

 options:  
     --all                                                  display all thread results instead of the first page
 -h, --help                                                 this help
 -b, --include-blocking-thread                              find the thread who is holding a lock that blocks the most number of threads.
     --lockedmonitors                                       find the thread info with lockedmonitors flag, default value is false.
     --lockedsynchronizers                                  find the thread info with lockedsynchronizers flag, default value is false.
 -i, --sample-interval <value>                              specify the sampling interval (in ms) when calculating cpu usage.
     --state <value>                                        display the thead filter by the state. new, runnable, timed_waiting, waiting, blocked, terminated is optional.
 -n, --top-n-threads <value>                                the number of thread(s) to show, ordered by cpu utilization, -1 to show all.
 <id>                                                       show thread stack
$ thread -i 5000
## 获取时间跨度为5s的计算汇总数据

$ thread -n 3
## 根据 cpu 使用率排序,获取从高到低的 3 个线程堆栈信息

$ thread -b
## 仅查看死锁线程的堆栈信息

$ thread --lockedsynchronizers
## 仅查看同步器死锁的线程堆栈信息

stop / exit 停止 和 离开

stop: 停止和退出 arthas consol ,正常退出步骤。

exit: 仅离开 arthas consol,但是绑定到 java 进程的 arthas 任务不会退出。

[shell]# java -jar arthas-boot.jar
[info] arthas-boot version: 3.5.3
[info] found existing java process, please choose one and input the serial number of the process, eg : 1. then hit enter.
* [1]: 5201 cloud-access-auth-1.18.1.jar
  [2]: 14419 tsf-stack-base-1.0.0.jar
  [3]: 27862 cloud-access-gateway-1.18.1.jar
  [4]: 6550 tsfmanager-operation-1.29.1.jar
1
[info] arthas home: /root/.arthas/lib/3.5.4/arthas
[info] try to attach process 5201
[info] attach process 5201 success.
[info] arthas-client connect 127.0.0.1 3658
  ,---.  ,------. ,--------.,--.  ,--.  ,---.   ,---.  
 /  o  \ |  .--. ''--.  .--'|  '--'  | /  o  \ '   .-' 
|  .-.  ||  '--'.'   |  |   |  .--.  ||  .-.  |`.  `-. 
|  | |  ||  |\  \    |  |   |  |  |  ||  | |  |.-'    |
`--' `--'`--' '--'   `--'   `--'  `--'`--' `--'`-----' 

wiki       https://arthas.aliyun.com/doc
tutorials  https://arthas.aliyun.com/doc/arthas-tutorials.html
version    3.5.4
main_class
pid        5201
time       2021-09-03 13:05:51

[arthas@5201]$ exit


[shell]# java -jar arthas-boot.jar
[info] arthas-boot version: 3.5.3
[info] process 5201 already using port 3658				## 由于上次并没有 shutdown 关闭arthas与java进程的绑定,所以arthas重新启动的时候,检测到仍然绑定到 5201 进程上面的。
[info] process 5201 already using port 8563
[info] found existing java process, please choose one and input the serial number of the process, eg : 1. then hit enter.
* [1]: 5201 cloud-access-auth-1.18.1.jar
  [2]: 14419 tsf-stack-base-1.0.0.jar
  [3]: 27862 cloud-access-gateway-1.18.1.jar
  [4]: 6550 tsfmanager-operation-1.29.1.jar

我们通过 jstack -l 5201 来证实这一点

[root@vm-0-4-centos ~]# jstack -l 5201 | more
2021-09-03 13:08:16
full thread dump openjdk 64-bit server vm (25.302-b08 mixed mode):

"arthas-nettyhttptelnetbootstrap-3-3" #169 daemon prio=5 os_prio=0 tid=0x00007f314000b800 nid=0x5632 runnable [0x00007f30cb51a000]
   java.lang.thread.state: runnable
	at sun.nio.ch.epollarraywrapper.epollwait(native method)
	at sun.nio.ch.epollarraywrapper.poll(epollarraywrapper.java:269)
	at sun.nio.ch.epollselectorimpl.doselect(epollselectorimpl.java:93)
	at sun.nio.ch.selectorimpl.lockanddoselect(selectorimpl.java:86)
	- locked <0x00000000e8cafb00> (a com.alibaba.arthas.deps.io.netty.channel.nio.selectedselectionkeyset)
	- locked <0x00000000e8caf8a8> (a java.util.collections$unmodifiableset)
	- locked <0x00000000e8caf790> (a sun.nio.ch.epollselectorimpl)
	at sun.nio.ch.selectorimpl.select(selectorimpl.java:97)
	at sun.nio.ch.selectorimpl.select(selectorimpl.java:101)
	at com.alibaba.arthas.deps.io.netty.channel.nio.selectedselectionkeysetselector.select(selectedselectionkeysetselector.java:68)
	at com.alibaba.arthas.deps.io.netty.channel.nio.nioeventloop.select(nioeventloop.java:810)
	at com.alibaba.arthas.deps.io.netty.channel.nio.nioeventloop.run(nioeventloop.java:457)
	at com.alibaba.arthas.deps.io.netty.util.concurrent.singlethreadeventexecutor$4.run(singlethreadeventexecutor.java:989)
	at com.alibaba.arthas.deps.io.netty.util.internal.threadexecutormap$2.run(threadexecutormap.java:74)
	at com.alibaba.arthas.deps.io.netty.util.concurrent.fastthreadlocalrunnable.run(fastthreadlocalrunnable.java:30)
	at java.lang.thread.run(thread.java:748)

   locked ownable synchronizers:
	- none

"arthas-nettyhttptelnetbootstrap-3-2" #168 daemon prio=5 os_prio=0 tid=0x00007f314000a000 nid=0x51ce runnable [0x00007f30d09f9000]
   java.lang.thread.state: runnable
	at sun.nio.ch.epollarraywrapper.epollwait(native method)
	at sun.nio.ch.epollarraywrapper.poll(epollarraywrapper.java:269)
	at sun.nio.ch.epollselectorimpl.doselect(epollselectorimpl.java:93)
	at sun.nio.ch.selectorimpl.lockanddoselect(selectorimpl.java:86)
	- locked <0x00000000e8cac058> (a com.alibaba.arthas.deps.io.netty.channel.nio.selectedselectionkeyset)
	- locked <0x00000000e8cabe00> (a java.util.collections$unmodifiableset)
	- locked <0x00000000e8cabce8> (a sun.nio.ch.epollselectorimpl)
	at sun.nio.ch.selectorimpl.select(selectorimpl.java:97)
	at sun.nio.ch.selectorimpl.select(selectorimpl.java:101)
	at com.alibaba.arthas.deps.io.netty.channel.nio.selectedselectionkeysetselector.select(selectedselectionkeysetselector.java:68)

我们可以看到 5201 进程的java堆栈信息,有 arthas 的线程正在运行中。

正常退出步骤:

[arthas@5201]$ stop
resetting all enhanced classes ...
affect(class count: 0 , method count: 0) cost in 0 ms, listenerid: 0
arthas server is going to shutdown...
[arthas@5201]$ session (f0151617-7fd2-4b4b-b79f-31d366a72fc5) is closed because server is going to shutdown.




[shell]# jstack -l 5201 | more
2021-09-03 13:10:16
full thread dump openjdk 64-bit server vm (25.302-b08 mixed mode):

"abandoned connection cleanup thread" #51 daemon prio=5 os_prio=0 tid=0x00007f30e0246000 nid=0x1d86 in object.wait() [0x00007f3120393000]
   java.lang.thread.state: timed_waiting (on object monitor)
	at java.lang.object.wait(native method)
	at java.lang.ref.referencequeue.remove(referencequeue.java:144)
	- locked <0x00000000e3280300> (a java.lang.ref.referencequeue$lock)
	at com.mysql.jdbc.abandonedconnectioncleanupthread.run(abandonedconnectioncleanupthread.java:64)
	at java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1149)
	at java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:624)
	at java.lang.thread.run(thread.java:748)

   locked ownable synchronizers:
	- <0x00000000e3280390> (a java.util.concurrent.threadpoolexecutor$worker)

"tomcat jdbc pool cleaner[1450495309:1630634377161]" #50 daemon prio=5 os_prio=0 tid=0x00007f30e01e4800 nid=0x1d85 in object.wait() [0x00007f3120494000]
   java.lang.thread.state: timed_waiting (on object monitor)
	at java.lang.object.wait(native method)
	at java.util.timerthread.mainloop(timer.java:552)
	- locked <0x00000000e3280540> (a java.util.taskqueue)
	at java.util.timerthread.run(timer.java:505)

   locked ownable synchronizers:
	- none

可以看到,使用 stop 指令关闭arthas诊断程序后,java 进程上面的arthas线程绑定也一并退出了。

watch 指令 ⭐ -- 方法执行数据观测

watch指令算是 arthas 中最常用的指令之一了,它能够获取指定包.类.方法入参自身类方法体内部对象以及返回对象值

[arthas@5201]$ watch -h
 usage:  
   watch [-b] [-e] [--exclude-class-pattern <value>] [-x <value>] [-f] [-h] [-n <value>] [--listenerid <value>] [-e] [-m <value>] [-s] [-v] class-pattern method-pattern [express] [condition-express]

 summary:  
   display the input/output parameter, return object, and thrown exception of specified method invocation
   the express may be one of the following expression (evaluated dynamically):
           target : the object
            clazz : the object's class
           method : the constructor or method
           params : the parameters array of method
     params[0..n] : the element of parameters array
        returnobj : the returned object of method
         throwexp : the throw exception of method
         isreturn : the method ended by return
          isthrow : the method ended by throwing exception
            #cost : the execution time in ms of method invocation
 examples:     
   watch org.apache.commons.lang.stringutils isblank
   watch org.apache.commons.lang.stringutils isblank '{params, target, returnobj, throwexp}' -x 2
   watch *stringutils isblank params[0] params[0].length==1
   watch *stringutils isblank params '#cost>100'
   watch -f *stringutils isblank params
   watch *stringutils isblank params[0]
   watch -e -b org\.apache\.commons\.lang\.stringutils isblank params[0]
   watch javax.servlet.filter * --exclude-class-pattern com.demo.testfilter
                                                                                                                                                                                                                 
 wiki:                                      
   https://arthas.aliyun.com/doc/watch

 options:  
 -b, --before                                                          watch before invocation
 -e, --exception                                                       watch after throw exception
     --exclude-class-pattern <value>                                   exclude class name pattern, use either '.' or '/' as separator
 -x, --expand <value>                                                  expand level of object (1 by default)
 -f, --finish                                                          watch after invocation, enable by default
 -h, --help                                                            this help
 -n, --limits <value>                                                  threshold of execution times
     --listenerid <value>                                              the special listenerid
 -e, --regex                                                           enable regular expression to match (wildcard matching by default)
 -m, --sizelimit <value>                                               upper size limit in bytes for the result (10 * 1024 * 1024 by default)
 -s, --success                                                         watch after successful invocation
 -v, --verbose                                                         enables print verbose information, default value false.
 <class-pattern>                                                       the full qualified class name you want to watch
 <method-pattern>                                                      the method name you want to watch
 <express>                                                             the content you want to watch, written by ognl. default value is '{params, target, returnobj}'
                                                                       examples:
                                                                         params
                                                                         params[0]
                                                                         'params[0]+params[1]'
                                                                         '{params[0], target, returnobj}'
                                                                         returnobj
                                                                         throwexp
                                                                         target
                                                                         clazz
                                                                         method

 <condition-express>                                                   conditional expression in ognl style, for example:
                                                                         true  : 1==1
                                                                         true  : true
                                                                         false : false
                                                                         true  : 'params.length>=0'
                                                                         false : 1==2
                                                                         '#cost>100'

参数说明

参数名称 参数说明
class-pattern 类名表达式匹配
method-pattern 方法名表达式匹配
express 观察表达式,默认值:{params, target, returnobj}
condition-express 条件表达式
[b] 在方法调用之前观察
[e] 在方法异常之后观察
[s] 在方法返回之后观察
[f] 在方法结束之后(正常返回和异常返回)观察
[e] 开启正则表达式匹配,默认为通配符匹配
[x:] 指定输出结果的属性遍历深度,默认为 1

这里重点要说明的是观察表达式,观察表达式的构成主要由 #ognl 表达式组成,所以你可以这样写"{params,returnobj}",只要是一个合法的 ognl 表达式,都能被正常支持。

观察的维度也比较多,主要体现在参数 advice 的数据结构上。advice 参数最主要是封装了通知节点的所有信息。请参考表达式核心变量中关于该节点的描述。

使用举例:

我需要观察cloud-access-auth-1.18.1.jar进程在处理登录信息时的登录方法信息,日志如下:

13:42:54.205 info  [http-nio-7001-exec-4] c.t.c.access.sso.service.impl.authenticateservice - [access auth] account login parameter. accountname:qcloudadmin ,password:******

得到指定类名为authenticateservice

我们带到 arthas 中进行 watch:

### 报名在日志文件中是简写,所以我这里使用通配符方式匹配类名,第二个参数方法名我也用*代替,全部匹配
[arthas@5201]$ watch *authenticateservice *
press q or ctrl+c to abort.
affect(class count: 2 , method count: 6) cost in 130 ms, listenerid: 16
### 从输出信息得知,在这个 java 进程所有代码中匹配到有两个类,一共6个方法

我们来点击页面登录按钮,看看 watch 中能观察到哪些动作:

[arthas@5201]$ watch *authenticateservice *
press q or ctrl+c to abort.
affect(class count: 2 , method count: 6) cost in 130 ms, listenerid: 16
    
#### 第一个方法开始执行 begin
method=com.tencent.cloud.access.sso.service.impl.authenticateservice.login location=atexit
ts=2021-09-03 13:51:25; [cost=2.217281ms] result=@arraylist[
    @object[][isempty=false;size=3],
    @authenticateservice[com.tencent.cloud.access.sso.service.impl.authenticateservice@f5cadbf],
    @accessauthprincipal[com.tencent.cloud.access.sso.model.accessauthprincipal@72f71bf6],
]
#### 第一个方法执行结束 end
    
#### 第二个方法开始执行 begin
method=com.tencent.cloud.access.sso.service.impl.authenticateservice.updatesession location=atexit
ts=2021-09-03 13:51:25; [cost=0.956478ms] result=@arraylist[
    @object[][isempty=false;size=2],
    @authenticateservice[com.tencent.cloud.access.sso.service.impl.authenticateservice@f5cadbf],
    @authenticationresponse[com.tencent.cloud.access.sso.model.authenticationresponse@6b2bae10],
]
#### 第二个方法执行退出 end
..............

在输出信息中我们可以看到,第一行有完整的方法路径,以及获取的退出状态location

  • atexit:表示正常退出。
  • atexceptionexit:表示异常退出。

第二行有方法执行的开始时间戳以及cost 开销 ,最后一个为watch的结果。

这里result的 arraylist 数组是 watch 指令的强大之处,它默认包含三个对象:

  • params: 入参,通常为数组,这里为 @object 对象
  • target: 运行中当前 this 对象,也就是这个类对象本身,这里为@authenticateservice实体类对象
  • returnobj: 返回对象值,这里为返回的@accessauthprincipal对象

我们重新执行一次 watch 指令,这次咱们精确指定类名和方法名,以及加一个-x解析深度参数:

[arthas@5201]$ watch com.tencent.cloud.access.sso.service.impl.authenticateservice login -x 2
press q or ctrl+c to abort.
affect(class count: 1 , method count: 2) cost in 74 ms, listenerid: 17
method=com.tencent.cloud.access.sso.service.impl.authenticateservice.login location=atexit
ts=2021-09-03 14:10:15; [cost=3.289679ms] result=@arraylist[
    @object[][
        @string[qcloudadmin],
        @string[bgi8c0yc+iavrlkuqry6klq6t2j/9pnrl6g/+kx9ppe=],
        @string[127.0.0.1],
    ],
    @authenticateservice[
        log=@logger[logger[com.tencent.cloud.access.sso.service.impl.authenticateservice]],
        sessiondao=@redissessiondao[com.tencent.cloud.access.sso.shiro.redissessiondao@61813e98],
        accountsessionservice=@accountsessionservice[com.tencent.cloud.access.account.service.impl.accountsessionservice@30e815ac],
        accessauthrealm=@accessauthrealm[com.tencent.cloud.access.sso.shiro.accessauthrealm@1faea5],
        accountservice=@accountservice[com.tencent.cloud.access.account.service.impl.accountservice@197459d8],
        ssoproperties=@ssoproperties[com.tencent.cloud.access.sso.config.ssoproperties@461879b2],
        securitymanager=@defaultsecuritymanager[org.apache.shiro.mgt.defaultsecuritymanager@3b0f92f0],
        ssoservice=@qcloudssoservice[com.tencent.cloud.access.sso.service.impl.qcloudssoservice@4f8704f5],
        userservice=@userservice[com.tencent.cloud.access.user.service.impl.userservice@5e69da74],
    ],
    @accessauthprincipal[
        serialversionuid=@long[-2856270666386831504],
        accountname=@string[qcloudadmin],
        userid=null,
        accountid=@string[account-96a79v5b],
        password=@string[vyuqejrc5ejq21t/f9rb1djm+4+eanqxy3zkw2oiiwa=],
        servicecode=null,
        isadmin=null,
        loginname=null,
        serialversionuid=@long[8229738167949958388],
        token=@string[54158a08d8104de57a855249eb6ffe06],
        serialversionuid=@long[-4556824360581761962],
        appid=null,
        subaccountuin=null,
        uin=null,
        requestid=null,
        region=null,
        kv=null,
    ],
]
    
method=com.tencent.cloud.access.sso.service.impl.authenticateservice.login location=atexit
ts=2021-09-03 14:10:15; [cost=9.571541ms] result=@arraylist[
    @object[][
        @loginrequest[com.tencent.cloud.access.sso.model.loginrequest@3dd2bbb0],
    ],
    @authenticateservice[
        log=@logger[logger[com.tencent.cloud.access.sso.service.impl.authenticateservice]],
        sessiondao=@redissessiondao[com.tencent.cloud.access.sso.shiro.redissessiondao@61813e98],
        accountsessionservice=@accountsessionservice[com.tencent.cloud.access.account.service.impl.accountsessionservice@30e815ac],
        accessauthrealm=@accessauthrealm[com.tencent.cloud.access.sso.shiro.accessauthrealm@1faea5],
        accountservice=@accountservice[com.tencent.cloud.access.account.service.impl.accountservice@197459d8],
        ssoproperties=@ssoproperties[com.tencent.cloud.access.sso.config.ssoproperties@461879b2],
        securitymanager=@defaultsecuritymanager[org.apache.shiro.mgt.defaultsecuritymanager@3b0f92f0],
        ssoservice=@qcloudssoservice[com.tencent.cloud.access.sso.service.impl.qcloudssoservice@4f8704f5],
        userservice=@userservice[com.tencent.cloud.access.user.service.impl.userservice@5e69da74],
    ],
    @authenticationresponse[
        serialversionuid=@long[-6134589862066278677],
        token=@string[54158a08d8104de57a855249eb6ffe06],
        accountid=@string[account-96a79v5b],
        changepwd=@string[n],
        users=@arraylist[isempty=false;size=1],
    ],
]
..............

watch 指令的-x选项表示解析三个阶段的对象深度,默认值为 1,也就是只解析到对象层,不解析对象的下一级属性等信息。

通过上述指令,我们获取到了更加详细的入参、this对象、返回值的信息,依次解析如下:

params 方法入参:

  • @string[qcloudadmin]: 参数一,用户名
  • @string[bgi8c0yc+iavrlkuqry6klq6t2j/9pnrl6g/+kx9ppe=]: 密码加密串
  • @string[127.0.0.1]: 来源主机信息

this方法体内部对象:

returnobj 返回值对象,这里为@accessauthprincipal对象:

  • serialversionuid: 用户
  • uidaccountname: 登录用户名
  • password: 用户密码加密串token: token串
  • ........

条件表达式过滤

[arthas@5201]$ watch com.tencent.cloud.access.sso.service.impl.authenticateservice login '{params[0]=qcloudadmin,returnobj}' -x 2

诊断返回信息包含params[0]returnobj对象,而且仅获取入参params[0] == "qcloudadmin"的方法调用,最后解析深度为 2。

只有满足条件的调用,才会被 arthas 捕获到。

观察异常信息

[arthas@5201]$ watch com.tencent.cloud.access.sso.service.impl.authenticateservice login '{params[0],throwexp}' -e -x 2

  • -e: 表示在抛出异常之后观察
  • express观察表达式第二个参数throwexp: 表示异常信息的变量是throwexp

按方法执行耗时进行过滤

[arthas@5201]$ watch com.tencent.cloud.access.sso.service.impl.authenticateservice login '{params[0],returnobj}' '#cost>200' -x 2

  • watch指令的第四个参数 condition-express#cost>200,表示诊断处理耗时大于 200ms 才会被捕获输出。
  • -x 2: 解析深度为 2。

仅观察当前对象的属性

[arthas@5201]$ watch com.tencent.cloud.access.sso.service.impl.authenticateservice login 'target' -x 3
press q or ctrl+c to abort.
affect(class count: 1 , method count: 2) cost in 76 ms, listenerid: 23
method=com.tencent.cloud.access.sso.service.impl.authenticateservice.login location=atexit
ts=2021-09-03 14:48:33; [cost=3.189525ms] result=@authenticateservice[
    log=@logger[
        serialversionuid=@long[5454405123156820674],
        fqcn=@string[ch.qos.logback.classic.logger],
        name=@string[com.tencent.cloud.access.sso.service.impl.authenticateservice],
        level=null,
        effectivelevelint=@integer[20000],
        parent=@logger[
            serialversionuid=@long[5454405123156820674],
            fqcn=@string[ch.qos.logback.classic.logger],
            name=@string[com.tencent.cloud.access.sso.service.impl],
            level=null,
            effectivelevelint=@integer[20000],
            parent=@logger[logger[com.tencent.cloud.access.sso.service]],
            childrenlist=@copyonwritearraylist[isempty=false;size=2],
            aai=null,
            additive=@boolean[true],
            loggercontext=@loggercontext[ch.qos.logback.classic.loggercontext[default]],
        ],
        childrenlist=null,
        aai=null,
        additive=@boolean[true],
        loggercontext=@loggercontext[
            default_packaging_data=@boolean[false],
            root=@logger[logger[root]],
            size=@integer[501],
            noappenderwarning=@integer[0],
            loggercontextlistenerlist=@arraylist[isempty=false;size=1],
            loggercache=@concurrenthashmap[isempty=false;size=501],
            loggercontextremoteview=@loggercontextvo[loggercontextvo{name='default', propertymap={}, birthtime=1630634095948}],
            turbofilterlist=@turbofilterlist[isempty=true;size=0],
            packagingdataenabled=@boolean[false],
            maxcallerdatadepth=@integer[8],
            resetcount=@integer[2],
            frameworkpackages=@arraylist[isempty=true;size=0],
            birthtime=@long[1630634095948],
            name=@string[default],
            sm=@basicstatusmanager[ch.qos.logback.core.basicstatusmanager@612c57fb],
            propertymap=@hashmap[isempty=true;size=0],
            objectmap=@hashmap[isempty=false;size=6],
            configurationlock=@logbacklock[ch.qos.logback.core.spi.logbacklock@36566db5],
            scheduledexecutorservice=null,
            scheduledfutures=@arraylist[isempty=true;size=0],
            lifecyclemanager=@lifecyclemanager[ch.qos.logback.core.lifecyclemanager@44477e6],
            started=@boolean[false],
        ],
    ],
    sessiondao=@redissessiondao[
      .............

扩展思维,我们可以直接透过一次调用,观察到底层连接 jdbc 的信息:

[arthas@5201]$ watch com.tencent.cloud.access.sso.service.impl.authenticateservice login 'target.userservice.userdao.jdbctemplate.datasource.pool.poolproperties.url' -x 2
press q or ctrl+c to abort.
affect(class count: 1 , method count: 2) cost in 69 ms, listenerid: 34
method=com.tencent.cloud.access.sso.service.impl.authenticateservice.login location=atexit
ts=2021-09-03 15:09:55; [cost=2.682966ms] result=@string[jdbc:mysql://*.*.*.*:3306/access_auth?usessl=false&characterencoding=utf8]
                                                        
method=com.tencent.cloud.access.sso.service.impl.authenticateservice.login location=atexit
ts=2021-09-03 15:09:55; [cost=21.373065ms] result=@string[jdbc:mysql://*.*.*.*:3306/access_auth?usessl=false&characterencoding=utf8]

这里就从顶层往下,获取到了该次调用,涉及到查库的 jdbc datasource 连接配置信息。

result返回的是一个 string 类型对象,值为 jdbc:mysql://*.*.*.*:3306/access_auth?usessl=false&characterencoding=utf8

排除指定的类

[arthas@5201]$ watch com.tencent.cloud.access.sso.service.impl.* * 'target' -x 1 --exclude-class-pattern authorizeservice | grep --color authorizeservice
press q or ctrl+c to abort.
  • --exclude-class-pattern:排除指定的类

trace 指令 ⭐

方法内部调用路径,并输出方法路径上的每个节点上耗时

trace 命令能主动搜索 class-patternmethod-pattern 对应的方法调用路径,渲染和统计整个调用链路上的所有性能开销和追踪调用链路

参数说明

参数名称 参数说明
class-pattern 类名表达式匹配
method-pattern 方法名表达式匹配
condition-express 条件表达式
[e] 开启正则表达式匹配,默认为通配符匹配
[n:] 命令执行次数
#cost 方法执行耗时
这里重点要说明的是观察表达式,观察表达式的构成主要由 #ognl 表达式组成,所以你可以这样写"{params,returnobj}",只要是一个合法的 ognl 表达式,都能被正常支持。

观察的维度也比较多,主要体现在参数 advice 的数据结构上。advice 参数最主要是封装了通知节点的所有信息。

请参考表达式核心变量中关于该节点的描述。

很多时候我们只想看到某个方法的rt大于某个时间之后的trace结果,现在arthas可以按照方法执行的耗时来进行过滤了,例如trace *stringutils isblank '#cost>100'表示当执行时间超过100ms的时候,才会输出trace的结果。

watch/stack/trace这个三个命令都支持#cost

使用举例:

[arthas@5201]$ trace com.tencent.cloud.access.sso.service.impl.authenticateservice login
press q or ctrl+c to abort.
affect(class count: 1 , method count: 2) cost in 114 ms, listenerid: 49
`---ts=2021-09-03 15:37:52;thread_name=http-nio-7001-exec-5;id=18;is_daemon=true;priority=5;tccl=org.springframework.boot.context.embedded.tomcat.tomcatembeddedwebappclassloader@1cfd053
    `---[6.69059ms] com.tencent.cloud.access.sso.service.impl.authenticateservice:login()
        +---[0.045058ms] com.tencent.cloud.access.sso.model.loginrequest:getopt() #87
        +---[0.011503ms] com.tencent.cloud.access.sso.constant.logintype:gettype() #88
        +---[0.004858ms] com.tencent.cloud.access.sso.constant.logintype:gettype() #89
        +---[0.005082ms] com.tencent.cloud.access.sso.model.loginrequest:getaccountname() #93
        +---[0.005074ms] com.tencent.cloud.access.sso.model.loginrequest:getpassword() #94
        +---[min=0.002257ms,max=0.010395ms,total=0.012652ms,count=2] org.springframework.util.stringutils:isempty() #95
        +---[0.008128ms] com.tencent.cloud.access.sso.config.ssoproperties:ispasswordtextprintable() #100
        +---[0.084201ms] org.slf4j.logger:info() #99
        +---[0.00653ms] com.tencent.cloud.access.sso.model.authenticationresponse:<init>() #101
        +---[0.004871ms] com.tencent.cloud.access.sso.model.loginrequest:getremotehost() #102
        +---[3.317607ms] com.tencent.cloud.access.sso.service.impl.authenticateservice:login() #102
        |   `---[3.285177ms] com.tencent.cloud.access.sso.service.impl.authenticateservice:login()
        |       +---[0.008045ms] org.apache.shiro.authc.usernamepasswordtoken:<init>() #139
        |       +---[0.011232ms] org.apache.shiro.subject.simpleprincipalcollection:<init>() #141
        |       +---[0.00843ms] org.apache.shiro.subject.support.delegatingsubject:<init>() #142
        |       +---[0.015667ms] org.apache.shiro.util.threadcontext:bind() #143
        |       +---[1.051658ms] org.apache.shiro.subject.support.delegatingsubject:login() #144
        |       +---[0.988623ms] org.apache.shiro.subject.support.delegatingsubject:getsession() #145
        |       +---[0.015629ms] org.apache.shiro.session.session:getid() #146
        |       +---[0.323618ms] org.apache.shiro.subject.support.delegatingsubject:getprincipal() #147
        |       +---[0.009258ms] com.tencent.cloud.access.sso.model.accessauthprincipal:settoken() #149
        |       +---[0.007608ms] com.tencent.cloud.access.sso.model.accessauthprincipal:setaccountname() #150
        |       +---[0.429798ms] org.apache.shiro.session.session:setattribute() #151
        |       `---[0.207347ms] com.tencent.cloud.access.account.service.iaccountsessionservice:bind() #152
        +---[0.010654ms] com.tencent.cloud.access.account.account:<init>() #103
        +---[0.824315ms] com.tencent.cloud.access.account.service.iaccountservice:find() #103
        +---[0.006474ms] com.tencent.cloud.access.account.account:getlock() #104
        +---[0.004144ms] com.tencent.cloud.access.account.account:getchangepassword() #107
        +---[0.005663ms] com.tencent.cloud.access.sso.model.authenticationresponse:setchangepwd() #107
        +---[0.004683ms] com.tencent.cloud.access.sso.model.accessauthprincipal:gettoken() #108
        +---[0.00414ms] com.tencent.cloud.access.sso.model.authenticationresponse:settoken() #108
        +---[0.003733ms] com.tencent.cloud.access.account.account:getaccountid() #109
        +---[0.005164ms] com.tencent.cloud.access.sso.model.authenticationresponse:setaccountid() #109
        +---[0.002866ms] com.tencent.cloud.access.sso.model.accessauthprincipal:setaccountname() #110
        +---[0.00399ms] com.tencent.cloud.access.sso.model.accessauthprincipal:getaccountid() #112
        +---[0.014922ms] com.tencent.cloud.access.user.user:<init>() #112
        +---[0.004781ms] com.tencent.cloud.access.user.user:setappisolate() #113
        +---[0.83272ms] com.tencent.cloud.access.user.service.iuserservice:findaccountlist() #114
        +---[0.006398ms] com.tencent.cloud.access.user.user:getuserid() #116
        +---[0.005214ms] com.tencent.cloud.access.sso.model.accessauthprincipal:setuserid() #116
        +---[0.00349ms] com.tencent.cloud.access.sso.model.accessauthprincipal:gettoken() #118
        +---[0.002987ms] com.tencent.cloud.access.user.user:getuserid() #118
        +---[0.887095ms] com.tencent.cloud.access.sso.service.impl.authenticateservice:updatesession() #118
        `---[0.004734ms] com.tencent.cloud.access.sso.model.authenticationresponse:setusers() #120
`---ts=2021-09-03 15:37:52;thread_name=http-nio-7001-exec-1;id=14;is_daemon=true;priority=5;tccl=org.springframework.boot.context.embedded.tomcat.tomcatembeddedwebappclassloader@1cfd053
    `---[1.28437ms] com.tencent.cloud.access.sso.service.impl.authenticateservice:login()
        +---[0.003596ms] com.tencent.cloud.access.sso.model.loginrequest:getopt() #87
        +---[0.006076ms] com.tencent.cloud.access.sso.constant.logintype:gettype() #88
        +---[0.002865ms] com.tencent.cloud.access.sso.constant.logintype:gettype() #89
        +---[0.010558ms] com.tencent.cloud.access.sso.model.loginrequest:getaccesstoken() #123
        +---[0.003959ms] com.tencent.cloud.access.sso.model.loginrequest:getuid() #124
        +---[0.003368ms] org.springframework.util.stringutils:isempty() #125
        +---[0.002671ms] org.springframework.util.stringutils:isempty() #128
        `---[1.166953ms] com.tencent.cloud.access.sso.service.impl.authenticateservice:updatesession() #131

耗时过滤诊断

[arthas@5201]$ trace com.tencent.cloud.access.sso.service.impl.authenticateservice login '#cost > 2000'

#cost > 2000: 仅捕获开销时间大于 2000ms 的路径。

仅过滤方法一次调用

[arthas@5201]$ trace com.tencent.cloud.access.sso.service.impl.authenticateservice login -n 1

仅捕获一次指定方法的调用,然后退出任务。

sysprop 指令 -- 获取/设置进程系统属性

sysprop 主要用来查看、设置当前进程的系统属性信息。

使用举例

查看当前java进程的系统属性

[arthas@27878]$ sysprop
 key                                                   value
-------------------------------------------------------------------------
 awt.toolkit                                           sun.awt.x11.xtoolkit
 file.encoding.pkg                                     sun.io
 java.specification.version                            1.8
 sun.cpu.isalist
 sun.jnu.encoding                                      utf-8
 java.class.path                                       /data/tsf/tsf-oss/tsf-ratelimit/tsf-ratelimit-1.29.1/lib/tsf-ratelimit-1.29.1.jar
 java.vm.vendor                                        tencent
 sun.arch.data.model                                   64
 java.vendor.url                                       http://jdk.oa.com/
 catalina.usenaming                                    false
 user.timezone                                         asia/shanghai
 org.jboss.logging.provider                            slf4j
 os.name                                               linux
 java.vm.specification.version                         1.8
 @appid                                                tsf-ratelimit
 user.country                                          us
 sun.java.launcher                                     sun_standard
 sun.boot.library.path                                 /data/tencentkona-8.0.2-252/jre/lib/amd64
 sun.java.command                                      /data/tsf/tsf-oss/tsf-ratelimit/tsf-ratelimit-1.29.1/lib/tsf-ratelimit-1.29.1.jar
 sun.cpu.endian                                        little
 user.home                                             /root
 user.language                                         en
 java.specification.vendor                             oracle corporation
 java.home                                             /data/tencentkona-8.0.2-252/jre
 file.separator                                        /
 line.separator

 java.vm.specification.vendor                          oracle corporation
 java.specification.name                               java platform api specification
 java.awt.graphicsenv                                  sun.awt.x11graphicsenvironment
 java.awt.headless                                     true
 log_level_pattern                                     %5p [bootstrap,%x{x-b3-traceid:-},%x{x-b3-spanid:-},%x{x-span-export:-}]
 sun.boot.class.path                                   /data/tencentkona-8.0.2-252/jre/lib/resources.jar:/data/tencentkona-8.0.2-252/jre/lib/rt.jar:/data/tencentkona-8.0.2-252/jre/lib/sunrsasign.jar:/data/tencentkona-8.0.2-252/jre/lib/jsse.jar:/data/tencentkona-8.0.2-2
                                                       52/jre/lib/jce.jar:/data/tencentkona-8.0.2-252/jre/lib/charsets.jar:/data/tencentkona-8.0.2-252/jre/lib/jfr.jar:/data/tencentkona-8.0.2-252/jre/classes
 java.protocol.handler.pkgs                            org.springframework.boot.loader
 sun.management.compiler                               hotspot 64-bit tiered compilers
 java.runtime.version                                  1.8.0_252-b1
 java.net.preferipv4stack                              true
 user.name                                             root
 path.separator                                        :
 os.version                                            3.10.0-1127.19.1.el7.x86_64
 java.endorsed.dirs                                    /data/tencentkona-8.0.2-252/jre/lib/endorsed
 java.runtime.name                                     openjdk runtime environment
 file.encoding                                         utf-8
 spring.beaninfo.ignore                                true
 sun.nio.ch.buglevel
 java.vm.name                                          openjdk 64-bit server vm
 log_file                                              /var/log/tsf-oss/tsf-ratelimit/tsf-ratelimit
 java.vendor.url.bug                                   http://ce.oa.com/bia
 java.io.tmpdir                                        /tmp
 catalina.home                                         /tmp/tomcat.8220305148167761737.23000
 java.version                                          1.8.0_252
 user.dir                                              /data/tsf/tsf-oss/tsf-ratelimit/tsf-ratelimit-1.29.1
 os.arch                                               amd64
 pid                                                   27878
 java.vm.specification.name                            java virtual machine specification
 java.awt.printerjob                                   sun.print.psprinterjob
 sun.os.patch.level                                    unknown
 catalina.base                                         /tmp/tomcat.8220305148167761737.23000
 loader.path                                           /data/tsf/tsf-oss/tsf-ratelimit/tsf-ratelimit-1.29.1/config
 java.library.path                                     /data/tsf/tsf-oss/tsf-ratelimit/tsf-ratelimit-1.29.1/lib::/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
 java.vm.info                                          mixed mode, sharing
 java.vendor                                           tencent
 java.vm.version                                       25.252-b1
 java.ext.dirs                                         /data/tencentkona-8.0.2-252/jre/lib/ext:/usr/java/packages/lib/ext
 sun.io.unicode.encoding                               unicodelittle
 java.class.version                                    52.0

临时设置当前进程的系统属性

[arthas@29749]$ sysprop java.class.path /data/jdk/latest
successfully changed the system property.
 key                                                   value
-----------------------------------------------------------------------------------
 java.class.path                                       /data/jdk/latest

logger 指令 -- *查看or设置logger

参数说明

[arthas@29749]$ logger -h
 usage:      
   logger [-c <value>] [--classloaderclass <value>] [-h] [--include-no-appender] [-l <value>] [-n <value>]

 summary:    
   print logger info, and update the logger level
                                                                                                                               
 examples:    
   logger
   logger -c 327a647b
   logger -c 327a647b --name root --level debug
   logger --include-no-appender
                                                               
 wiki:         
   https://arthas.aliyun.com/doc/logger

 options: 
 -c, --classloader <value>                       classloader hashcode, if no value is set, default value is systemclassloader
     --classloaderclass <value>                  the class name of the special class's classloader.
 -h, --help                                      this help
     --include-no-appender                       include the loggers which don't have appenders, default value false
 -l, --level <value>                             set logger level
 -n, --name <value>                              logger name

使用举例

设置 logger 的 root appender 的日志级别

##### 获取 logger 类信息
[arthas@29749]$ logger
 name                                         root
 class                                        ch.qos.logback.classic.logger
 classloader                                  org.springframework.boot.loader.launchedurlclassloader@5674cd4d
 classloaderhash                              5674cd4d
 level                                        info
 effectivelevel                               info
 ......................

##### 设置 root 名称日志级别为 debug
[arthas@29749]$ logger -c 5674cd4d -n root -l debug

heapdump 指令 -- 堆转储

参数说明

[arthas@29749]$ heapdump -h
 usage:     
   heapdump [-h] [-l] [file]

 summary:   
   heap dump
              
 examples:    
   heapdump           ## hprof 文件保存到当前目录下
   heapdump --live    ## 活跃对象
   heapdump --live /tmp/dump.hprof
                                                             
 wiki:   
   https://arthas.aliyun.com/doc/heapdump

 options:     
 -h, --help                                          this help
 -l, --live                                          dump only live objects; if not specified, all objects in the heap are dumped.
 <file>                                              output file

sc 指令 -- 获取已加载类列表

参数说明

[arthas@29749]$  sc -h
 usage: 
   sc [-c <value>] [--classloaderclass <value>] [-d] [-x <value>] [-f] [-h] [-n <value>] [-e] class-pattern

 summary:  
   search all the classes loaded by jvm
                                   
 examples:  
   sc -d org.apache.commons.lang.stringutils
   sc -d org/apache/commons/lang/stringutils
   sc -d *stringutils
   sc -d -f org.apache.commons.lang.stringutils
   sc -e org\\.apache\\.commons\\.lang\\.stringutils
        
 wiki:     
   https://arthas.aliyun.com/doc/sc

 options:    
 -c, --classloader <value>                             the hash code of the special class's classloader
     --classloaderclass <value>                        the class name of the special class's classloader.
 -d, --details                                         display the details of class
 -x, --expand <value>                                  expand level of object (0 by default)
 -f, --field                                           display all the member variables
 -h, --help                                            this help
 -n, --limits <value>                                  maximum number of matching classes with details (100 by default)
 -e, --regex                                           enable regular expression to match (wildcard matching by default)
 <class-pattern>                                       class name pattern, use either '.' or '/' as separator

使用举例

#### 根据通配符获取已加载的包名类名列表
[arthas@29749]$ sc com.tencent.tsf.*
com.sun.proxy.$proxy132
com.sun.proxy.$proxy143
com.tencent.tsf.tsfapplicationstarter
com.tencent.tsf.tsfapplicationstarter$$enhancerbyspringcglib$$e6e6d3dc
com.tencent.tsf.common.tsfbaseentity
com.tencent.tsf.common.tsfpage
com.tencent.tsf.common.tsfpagequery
com.tencent.tsf.common.aop.controllercommonlog
..............

-d 参数获取具体类的基础信息:

[arthas@29749]$ sc com.tencent.tsf.tsfapplicationstarter -d
 class-info        com.tencent.tsf.tsfapplicationstarter
 code-source       file:/data/tsf/tsf-oss/tsf-ratelimit/tsf-ratelimit-1.29.1/lib/tsf-ratelimit-1.29.1.jar!/boot-inf/lib/tsf-common-1.29.1.jar!/
 name              com.tencent.tsf.tsfapplicationstarter
 isinterface       false
 isannotation      false
 isenum            false
 isanonymousclass  false
 isarray           false
 islocalclass      false
 ismemberclass     false
 isprimitive       false
 issynthetic       false
 simple-name       tsfapplicationstarter
 modifier          public
 annotation        org.springframework.boot.autoconfigure.springbootapplication,org.springframework.cloud.client.discovery.enablediscoveryclient,org.springframework.cloud.netflix.feign.enablefeignclients,org.springframework.transaction.annotation.enabletransactionmanag
                   ement,org.springframework.scheduling.annotation.enablescheduling,org.springframework.context.annotation.enableaspectjautoproxy
 interfaces
 super-class       +-java.lang.object
 class-loader      +-org.springframework.boot.loader.launchedurlclassloader@5674cd4d
                     +-sun.misc.launcher$appclassloader@70dea4e
                       +-sun.misc.launcher$extclassloader@65e2dbf3
 classloaderhash   5674cd4d

 class-info        com.tencent.tsf.tsfapplicationstarter$$enhancerbyspringcglib$$e6e6d3dc
 code-source       file:/data/tsf/tsf-oss/tsf-ratelimit/tsf-ratelimit-1.29.1/lib/tsf-ratelimit-1.29.1.jar!/boot-inf/lib/tsf-common-1.29.1.jar!/
 name              com.tencent.tsf.tsfapplicationstarter$$enhancerbyspringcglib$$e6e6d3dc
 isinterface       false
 isannotation      false
 isenum            false
 isanonymousclass  false
 isarray           false
 islocalclass      false
 ismemberclass     false
 isprimitive       false
 issynthetic       false
 simple-name       tsfapplicationstarter$$enhancerbyspringcglib$$e6e6d3dc
 modifier          public
 annotation
 interfaces        org.springframework.context.annotation.configurationclassenhancer$enhancedconfiguration
 super-class       +-com.tencent.tsf.tsfapplicationstarter
                     +-java.lang.object
 class-loader      +-org.springframework.boot.loader.launchedurlclassloader@5674cd4d
                     +-sun.misc.launcher$appclassloader@70dea4e
                       +-sun.misc.launcher$extclassloader@65e2dbf3
 classloaderhash   5674cd4d

affect(row-cnt:2) cost in 17 ms.

sm 指令 -- 获取指定类的method信息

该指令参数与 sc 指令参数类似。

使用举例:

##  获取 com.tencent.tsf.common.tsfpagequery 类的所有方法列表
[arthas@29749]$ sm com.tencent.tsf.common.tsfpagequery *
com.tencent.tsf.ratelimit.domain.ratelimit <init>(lcom/tencent/tsf/ratelimit/domain/ratelimit;)v
com.tencent.tsf.ratelimit.domain.ratelimit <init>()v
com.tencent.tsf.ratelimit.domain.ratelimit tostring()ljava/lang/string;
com.tencent.tsf.ratelimit.domain.ratelimit getrules()ljava/util/list;
com.tencent.tsf.ratelimit.domain.ratelimit lambda$containsin$0(lcom/tencent/tsf/ratelimit/domain/ratelimit$rule;lcom/tencent/tsf/ratelimit/domain/ratelimit$rule;)z
com.tencent.tsf.ratelimit.domain.ratelimit setrules(ljava/util/list;)v
com.tencent.tsf.ratelimit.domain.ratelimit isvalidrequest(z)z
com.tencent.tsf.ratelimit.domain.ratelimit getrequestidentity()ljava/lang/string;
com.tencent.tsf.ratelimit.domain.ratelimit setnamespaceid(ljava/lang/string;)v
com.tencent.tsf.ratelimit.domain.ratelimit containsin(ljava/util/list;)z
com.tencent.tsf.ratelimit.domain.ratelimit isdimensionconflict(ljava/util/list;)z
com.tencent.tsf.ratelimit.domain.ratelimit getnamespaceid()ljava/lang/string;
com.tencent.tsf.ratelimit.domain.ratelimit getservicename()ljava/lang/string;
com.tencent.tsf.ratelimit.domain.ratelimit setservicename(ljava/lang/string;)v
com.tencent.tsf.common.proxy.application <init>()v
com.tencent.tsf.common.proxy.application setapplicationid(ljava/lang/string;)v
com.tencent.tsf.common.proxy.application getmicroservicetype()ljava/lang/string;
com.tencent.tsf.common.proxy.application setmicroservicetype(ljava/lang/string;)v
com.tencent.tsf.common.proxy.application getapplicationid()ljava/lang/string;
com.tencent.tsf.ratelimit.proxy.microservice <init>()v
com.tencent.tsf.ratelimit.proxy.microservice setmicroservicename(ljava/lang/string;)v
com.tencent.tsf.ratelimit.proxy.microservice setnamespaceid(ljava/lang/string;)v
com.tencent.tsf.ratelimit.proxy.microservice getmicroservicename()ljava/lang/string;
com.tencent.tsf.ratelimit.proxy.microservice getnamespaceid()ljava/lang/string;
com.tencent.tsf.ratelimit.proxy.microservice getmicroserviceid()ljava/lang/string;
com.tencent.tsf.ratelimit.proxy.microservice setmicroserviceid(ljava/lang/string;)v
com.tencent.tsf.common.tsfpagequery <init>()v
com.tencent.tsf.common.tsfpagequery clear()v
com.tencent.tsf.common.tsfpagequery getoffset()ljava/lang/integer;
com.tencent.tsf.common.tsfpagequery setoffset(ljava/lang/integer;)v
com.tencent.tsf.common.tsfpagequery initdefault()v
com.tencent.tsf.common.tsfpagequery setsearchword(ljava/lang/string;)v
com.tencent.tsf.common.tsfpagequery getordertype()ljava/lang/integer;
com.tencent.tsf.common.tsfpagequery getordertypestr()ljava/lang/string;
com.tencent.tsf.common.tsfpagequery setordertype(ljava/lang/integer;)v
com.tencent.tsf.common.tsfpagequery getorderby()ljava/lang/string;
com.tencent.tsf.common.tsfpagequery setorderby(ljava/lang/string;)v
com.tencent.tsf.common.tsfpagequery getrealpage()i
com.tencent.tsf.common.tsfpagequery transerpagequery(lcom/tencent/tsf/common/tsfpagequery;)v
com.tencent.tsf.common.tsfpagequery getsearchwordlikestr()ljava/lang/string;
com.tencent.tsf.common.tsfpagequery getlimit()ljava/lang/integer;
com.tencent.tsf.common.tsfpagequery setlimit(ljava/lang/integer;)v
com.tencent.tsf.common.tsfpagequery getsearchword()ljava/lang/string;
affect(row-cnt:43) cost in 12 ms.

monitor 指令 -- 方法执行监控

该指令为非实时返回指令,默认 120s 返回一次统计值。

统计区间时间段内,方法执行的总数、成功次数、失败次数、平均执行率、失败比例 等信息。

参数说明

[arthas@8738]$ monitor -h
 usage:    
   monitor [-b] [-c <value>] [--exclude-class-pattern <value>] [-h] [-n <value>] [--listenerid <value>] [-e <value>] [-v] class-pattern method-pattern [condition-express]

 summary:  
   monitor method execution statistics, e.g. total/success/failure count, average rt, fail rate, etc.
                                                                          
 examples:    
   monitor org.apache.commons.lang.stringutils isblank
   monitor org.apache.commons.lang.stringutils isblank -c 5
   monitor org.apache.commons.lang.stringutils isblank params[0]!=null
   monitor -b org.apache.commons.lang.stringutils isblank params[0]!=null
   monitor -e org\.apache\.commons\.lang\.stringutils isblank
        
 wiki:     
   https://arthas.aliyun.com/doc/monitor

 options:   
 -b, --before                                           evaluate the condition-express before method invoke
 -c, --cycle <value>                                    the monitor interval (in seconds), 60 seconds by default
     --exclude-class-pattern <value>                    exclude class name pattern, use either '.' or '/' as separator
 -h, --help                                             this help
 -n, --limits <value>                                   threshold of execution times
     --listenerid <value>                               the special listenerid
 -e, --regex <value>                                    enable regular expression to match (wildcard matching by default)
 -v, --verbose                                          enables print verbose information, default value false.
 <class-pattern>                                        path and classname of pattern matching
 <method-pattern>                                       method of pattern matching
 <condition-express>                                    conditional expression in ognl style, for example:
                                                           true  : 1==1
                                                           true  : true
                                                           false : false
                                                           true  : 'params.length>=0'
                                                           false : 1==2
                                                           '#cost>100'

使用举例

[arthas@8738]$ monitor com.tencent.tsf.resource.ns.dao.namespacedao *
press q or ctrl+c to abort.
affect(class count: 1 , method count: 15) cost in 104 ms, listenerid: 6
 timestamp                 class                                         method            total      success  fail   avg-rt(ms)   fail-rate
----------------------------------------------------------------------------------------------------------------------------------------------------
 2021-09-09 18:26:58     com.tencent.tsf.resource.ns.dao.namespacedao   countlist          12          12      0     1.08              0.00%
 2021-09-09 18:26:58     com.tencent.tsf.resource.ns.dao.namespacedao   getauthwhereclause 28          28      0     0.18              0.00%
 2021-09-09 18:26:58     com.tencent.tsf.resource.ns.dao.namespacedao   findlist           2           2       0     1.09              0.00%

到此这篇关于arthas在线java进程诊断工具 在线调试神器的文章就介绍到这了,更多相关arthas在线java进程诊断工具 在线调试神器内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!