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

}
相关推荐
2501_9159214310 小时前
iOS 开发者工具推荐,构建从调试到性能优化的多维度生产力工具链(2025 深度工程向)
android·ios·性能优化·小程序·uni-app·iphone·webview
Chrison_mu11 小时前
Android项目背景动效-Kotlin
android·开发语言·kotlin
曾经的三心草12 小时前
JavaEE初阶-多线程2
android·java·java-ee
v***56513 小时前
Spring Cloud Gateway
android·前端·后端
苦逼的搬砖工15 小时前
基于 easy_rxdart 的轻量响应式与状态管理架构实践
android·flutter
2501_9159184115 小时前
苹果上架 iOS 应用的工程实践,一次从零到上线的完整记录
android·ios·小程序·https·uni-app·iphone·webview
從南走到北16 小时前
JAVA国际版同城跑腿源码快递代取帮买帮送同城服务源码支持Android+IOS+H5
android·java·ios·微信小程序
2501_9159184117 小时前
如何解析iOS崩溃日志:从获取到符号化分析
android·ios·小程序·https·uni-app·iphone·webview
Entropless17 小时前
OkHttp 深度解析(一) : 从一次完整请求看 OkHttp 整体架构
android·okhttp
v***913018 小时前
Spring+Quartz实现定时任务的配置方法
android·前端·后端