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;
    }

}
相关推荐
hunterandroid17 小时前
Android WebView JSBridge 治理实战:从线上白屏崩溃到协议化通信
android·前端
一个用户名i17 小时前
【Compose 系列】第 1 篇:认识 Compose,为什么要学它
android·android jetpack
极客猴子19 小时前
iPhone实时转写软件推荐:会议录音功能真实体验
android·人工智能·飞书
达令哥19 小时前
告别 ARouter!基于 Google 官方 Navigation 3 + KSP 打造 Compose 时代的双轨制路由框架
android·前端
YF021119 小时前
Android App启动与权限管控
android
嘟哩DuliDuli19 小时前
AI 短剧生成为什么要有角色库、场景库和镜头卡
android·人工智能·安全·ai·软件工程
NINO21 小时前
深度解析 Android ANR:从标准分析流程到 NativePollOnce 疑难破局
android
阿巴斯甜21 小时前
AppFunctions 完整介绍
android
蜡台1 天前
Jetpack Compose 从入门到精通
android·前端·kotlin·compose·jepack
toooooop81 天前
踩坑:PHP7.2导出Excel正常,升级7.3文件损坏需修复
android·excel