Java 编写查看调用栈信息

大家在开发项目的过程中,应该经常会需要分析调用栈信息,所以这里提供一个调用栈打印工具类,大家拿去直接用就行了

java 复制代码
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

public class StringLogUtils {
    public static String printStackTrace(Throwable throwable) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bos);
        String result = null;
        try {
            throwable.printStackTrace(ps);
            result = bos.toString();
        } finally {
            try {
                ps.close();
            } catch (Exception e) {

            }
        }
        return result;
    }

    public static String printStackTrace(Thread thread, boolean keepCallingFunction) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("Thread: " + thread.getName() + ", id: " + thread.getId() + ", Group: " + thread.getThreadGroup().getName() + ", state: " + thread.getState())
                .append("\n");
        int index = 2;
        if (!keepCallingFunction) {
            index++;
        }
        StackTraceElement[] trace = thread.getStackTrace();
        for (; index < trace.length; index++) {
            StackTraceElement traceElement = trace[index];
            stringBuilder.append("\tat " + traceElement)
                    .append("\n");
        }
        return stringBuilder.toString();
    }

    public static String printStackTrace(Thread thread) {
        return printStackTrace(thread, false);
    }

    public static String printStackTrace() {
        return printStackTrace(Thread.currentThread(), false);
    }

    public static String splitUrl(String url, String split, int index) {
        try {
            String[] arr = url.split(split);
            return arr[index];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
相关推荐
阿巴斯甜4 小时前
ARouter
android
Andya_net5 小时前
MySQL | MySQL 8.0 权限管理实践-精确赋予库、表只读等权限
android·数据库·mysql
阿巴斯甜6 小时前
Map
android
巫山老妖6 小时前
鹅厂十年:三段式技术成长复盘
android·人工智能·程序员
阿巴斯甜6 小时前
List集合
android
ooseabiscuit7 小时前
Laravel6.x核心优化与特性全解析
android·开发语言·javascript
阿巴斯甜8 小时前
Kotlin 协程 Coroutine
android
Jomurphys9 小时前
Compose 适配 - 通过 UiMediaScope 获取设备信息
android·compose
阿巴斯甜9 小时前
必看12
android
阿巴斯甜9 小时前
必看11
android