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

}
相关推荐
李堇3 小时前
android滚动列表VerticalRollingTextView
android·java
lxysbly4 小时前
n64模拟器安卓版带金手指2026
android
游戏开发爱好者87 小时前
日常开发与测试的 App 测试方法、查看设备状态、实时日志、应用数据
android·ios·小程序·https·uni-app·iphone·webview
王码码20357 小时前
Flutter for OpenHarmony 实战之基础组件:第三十一篇 Chip 系列组件 — 灵活的标签化交互
android·flutter·交互·harmonyos
黑码哥7 小时前
ViewHolder设计模式深度剖析:iOS开发者掌握Android列表性能优化的实战指南
android·ios·性能优化·跨平台开发·viewholder
亓才孓8 小时前
[JDBC]元数据
android
独行soc8 小时前
2026年渗透测试面试题总结-17(题目+回答)
android·网络·安全·web安全·渗透测试·安全狮
金融RPA机器人丨实在智能8 小时前
Android Studio开发App项目进入AI深水区:实在智能Agent引领无代码交互革命
android·人工智能·ai·android studio
科技块儿8 小时前
利用IP查询在智慧城市交通信号系统中的应用探索
android·tcp/ip·智慧城市
独行soc8 小时前
2026年渗透测试面试题总结-18(题目+回答)
android·网络·安全·web安全·渗透测试·安全狮