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

}
相关推荐
恋猫de小郭37 分钟前
iOS 26 正式版即将发布,Flutter 完成全新 devicectl + lldb 的 Debug JIT 运行支持
android·前端·flutter
幻雨様1 小时前
UE5多人MOBA+GAS 54、用户登录和会话创建请求
android·ue5
Just_Paranoid1 小时前
【SystemUI】锁屏来通知默认亮屏Wake模式
android·framework·systemui·keyguard·aod
没有了遇见1 小时前
Android +,++,+= 的区别
android·kotlin
_无_妄_3 小时前
Android 使用 WebView 直接加载 PDF 文件,通过 JS 实现
android
VomPom3 小时前
手写一个精简版Koin:深入理解依赖注入核心原理
android
Digitally4 小时前
如何轻松永久删除 Android 手机上的短信
android·智能手机
JulyYu5 小时前
Flutter混合栈适配安卓ActivityResult
android·flutter
Warren985 小时前
Appium学习笔记
android·windows·spring boot·笔记·后端·学习·appium