Mastering Arthas trace: Diagnose Java Method Chains Efficiently

This guide explains how to use Arthas's trace command to capture Java method call paths, measure execution time for each node, handle class and method patterns, and highlights its limitations with lambda expressions, providing practical code examples and output analysis.

FunTester
FunTester
FunTester
Mastering Arthas trace: Diagnose Java Method Chains Efficiently

What is Arthas?

Arthas is an open‑source Java diagnostic tool that provides powerful runtime inspection capabilities, including class loading, thread monitoring, and method tracing.

Key trace command

The trace command records the internal call chain of a method and reports the time spent at each node. It can actively search for class-pattern / method-pattern to render and aggregate the performance cost of the entire call chain.

Advanced usage

Advanced features rely on Arthas's OGNL support. Users can explore OGNL syntax for more complex tracing scenarios, though support for lambda expressions remains limited.

Sample trace output

[arthas@71728]$ trace com.fun.frame.httpclient.FanLibrary getHttpResponse
Press Q or Ctrl+C to abort.
Affect(class-cnt:2 , method-cnt:1) cost in 107 ms.
`---ts=2020-05-16 14:38:18;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=...`
    `---[49.749941ms] com.fun.frame.httpclient.FanLibrary:getHttpResponse()
        +---[0.100454ms] com.fun.frame.httpclient.FanLibrary:isRightRequest() #322
        +---[0.732549ms] com.fun.frame.httpclient.FanLibrary:beforeRequest() #323
        ... (additional stack frames with timing) ...

Illustrative Java code

package com.fun;

import com.alibaba.fastjson.JSONObject;
import com.fun.frame.httpclient.FanLibrary;
import org.apache.http.client.methods.HttpGet;

class sd extends FanLibrary {
    public static void main(String[] args) {
        while (true) {
            String url = "https://api.apiopen.top/getAllUrl";
            HttpGet get = getHttpGet(url);
            JSONObject response = getHttpResponse(get);
            output(response);
            output(test());
            sleep(5000);
        }
        testOver();
    }

    static String test() {
        sleep(1000);
        for (int i = 0; i < 5; i++) {
            getRandomInt(100);
        }
        ArrayList list = Arrays.asList(32, 432, 432, 423, 423, 32);
        list.stream().forEach({x -> output(x)});
        DEFAULT_STRING
    }
}

Implementation of getHttpResponse

/**
 * Retrieve response entity.
 * Automatically sets cookies; projects must manage cookies themselves.
 * Handles only text responses; file handling requires deprecated methods.
 */
public static JSONObject getHttpResponse(HttpRequestBase request) {
    if (!isRightRequest(request)) RequestException.fail(request);
    beforeRequest(request);
    JSONObject res = new JSONObject();
    RequestInfo requestInfo = new RequestInfo(request);
    if (HEADER_KEY) output("===========request header===========", Arrays.asList(request.getAllHeaders()));
    long start = Time.getTimeStamp();
    try (CloseableHttpResponse response = ClientManage.httpsClient.execute(request)) {
        long end = Time.getTimeStamp();
        long elapsed_time = end - start;
        if (HEADER_KEY) output("===========response header===========", Arrays.asList(response.getAllHeaders()));
        int status = getStatus(response, res);
        JSONObject setCookies = afterResponse(response);
        String content = getContent(response);
        int data_size = content.length();
        res.putAll(getJsonResponse(content, setCookies));
        int code = iBase == null ? -2 : iBase.checkCode(res, requestInfo);
        if (iBase != null && !iBase.isRight(res))
            new AlertOver("响应状态码错误:" + status, "状态码错误:" + status, requestInfo.getUrl(), requestInfo).sendSystemMessage();
        MySqlTest.saveApiTestDate(requestInfo, data_size, elapsed_time, status, getMark(), code, LOCAL_IP, COMPUTER_USER_NAME);
        if (SAVE_KEY) FunRequest.save(request, res);
    } catch (Exception e) {
        logger.warn("获取请求相应失败!", e);
        if (!requestInfo.isBlack())
            new AlertOver("接口请求失败", requestInfo.toString(), requestInfo.getUrl(), requestInfo).sendSystemMessage();
    } finally {
        HEADER_KEY = false;
        if (!requestInfo.isBlack()) {
            lastRequest = request;
        }
    }
    return res;
}

Limitations

The trace command does not handle lambda expressions well, which may require alternative tracing strategies for modern Java code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DebuggingJavaperformancediagnosticsArthastrace
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.