0
点赞
收藏
分享

微信扫一扫

【Arthas】使用 watch命令 线上诊断


如果debug线上环境但是又没有加日志,怎么办?可以使用arthas的watch命令来诊断。

测试程序:

/**
* Hello world!
*
*/

public class App
{
private List<Integer> p = new ArrayList<Integer>();
private static int num = 0;

private List<Data> get(){
p.add(0, num++);
Data data1 = new Data();
data1.map.put("key1", 1);
data1.map.put("key2",2);
data1.age = 10;
data1.name = "liyao";

Data data2 = new Data();
data2.map.put("key3",3);
List<Data> data = new ArrayList<Data>();
data.add(data1);
data.add(data2);
return data;
}

private void run(){
for (int i = 0; i < 1000000000; i++) {
try {
Thread.sleep(5000);
System.out.println(get());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main( String[] args ) throws IOException {

new App().run();
}
}

watch命令:

watch 全限定类名 方法名 观察点 参数

观察点:arthas定义了一系列的观察点:

​​https://alibaba.github.io/arthas/advice-class.html​​

常用的有:

target:调用方法的对象实例

params:方法参数

returnObj:返回值,如果有的话

returnExp:异常,如果有的话

如果只有一个观察点,可以直接写,比如:

watch com.liyao.App get returnObj

如果有多个,需要使用ognl表达式,放在”{}“里,使用,分割。

watch com.liyao.App get "{params,returnObj}"

参数:

有一个很常用的-x n,指定观察点的展开的层数,默认为1。如果我们想要观察对象内部的属性时,使用这个参数会很方便,不需要实现toString方法。

上面的例子:

不加-x参数:

$ watch com.liyao.App get "{returnObj, target}"
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 43 ms.
ts=2019-07-20 20:00:35; [cost=2.105606ms] result=@ArrayList[
    @ArrayList[isEmpty=false;size=2],
    @App[com.liyao.App@5680a178],
]
ts=2019-07-20 20:00:40; [cost=0.235734ms] result=@ArrayList[
    @ArrayList[isEmpty=false;size=2],
    @App[com.liyao.App@5680a178],
]

只显示了一层。如果想看里面的属性,可以使用-x参数,比如-x 3:

ts=2019-07-20 20:03:53; [cost=0.925101ms] result=@ArrayList[
    @App[
        p=@ArrayList[
            @Integer[7],
            @Integer[6],
            @Integer[5],
            @Integer[4],
            @Integer[3],
            @Integer[2],
            @Integer[1],
            @Integer[0],
        ],
        num=@Integer[8],
    ],
    @ArrayList[
        @Data[
            map=@HashMap[isEmpty=false;size=2],
            name=@String[liyao],
            age=@Integer[10],
        ],
        @Data[
            map=@HashMap[isEmpty=false;size=1],
            name=null,
            age=@Integer[0],
        ],
    ],
]

很方便。

举报

相关推荐

0 条评论