How can I get the current stack trace in Java?

前端 未结 21 3103
耶瑟儿~
耶瑟儿~ 2020-11-21 23:49

How do I get the current stack trace in Java, like how in .NET you can do Environment.StackTrace?

I found Thread.dumpStack() but it is not what I want -

21条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 00:23

    I have a utility method that returns a string with the stacktrace:

    static String getStackTrace(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        t.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }
    

    And just logit like...

    ... 
    catch (FileNotFoundException e) {
        logger.config(getStackTrace(e));
    }
    

提交回复
热议问题