Fetch only first N lines of a Stack Trace

大兔子大兔子 提交于 2020-01-12 18:45:29

问题


I have a Factory method that returns an object from a ID call.

Mock code:

public static Object getById(String id) {
    Object o = CRUD.doRecovery(Class, id);
    if(o == null) {
         printLogMessage("recovery by ID returned Null: " + id);
         // would really like to show only a few lines of stack trace.
    }
    return o;
}

How can I show only the first N lines of the stack trace (so I know the caller of the method) without dumping the whole stack trace on the log or having to rely on external libs?


回答1:


I'm assuming from what you are asking, that you don't have an exception to deal with. In which case you can get the current stack trace from:

StackTraceElement[] elements = Thread.currentThread().getStackTrace()

This will tell you pretty much everything you need to know about where you've come from in the code.




回答2:


You can use the ex.getStackTrace() to get the stack elements, the StackTraceElement contains one line of the full stacks, then print print what ever you want.

StackTraceElement[] elements = ex.getStackTrace();
print(elements[0]);



回答3:


This method displays i lines of the stack trace, skipping the first two.

public static String traceCaller(Exception ex, int i) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    StringBuilder sb = new StringBuilder();
    ex.printStackTrace(pw);
    String ss = sw.toString();
    String[] splitted = ss.split("\n");
    sb.append("\n");
    if(splitted.length > 2 + i) {
        for(int x = 2; x < i+2; x++) {
            sb.append(splitted[x].trim());
            sb.append("\n");
        }
        return sb.toString();
    }
    return "Trace too Short.";
}

The first two lines are the exception name and the method that called traceCaller(). Tweak it if you want to show these lines.

Thanks go to @BrianAgnew (stackoverflow.com/a/1149712/1532705) for the StringWriter PrintWriter idea




回答4:


If you just want to truncate the stack trace, you can print the entire stack trace to a StringWriter then remove what you don't want:

public static void main(String[] args) throws ParseException {
    try {
        throw new Exception("Argh!");
    } catch (Exception e) {
        System.err.println(shortenedStackTrace(e, 1));
    }
}

public static String shortenedStackTrace(Exception e, int maxLines) {
    StringWriter writer = new StringWriter();
    e.printStackTrace(new PrintWriter(writer));
    String[] lines = writer.toString().split("\n");
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < Math.min(lines.length, maxLines); i++) {
        sb.append(lines[i]).append("\n");
    }
    return sb.toString();
}

Alternatively, use e.getStackTrace() to obtain a StackTraceElement[] array. This gives you the caller stack (from inner to outer), but not the error message. You'll have to use e.getMessage() to get the error message.

Some logging frameworks can be configured to truncate stack traces automatically. E.g. see this question and answer about log4j configuration.

If you just want to see the stack trace at any point in the code, you can get the elements from the Thread.currentThread() object:

Thread.currentThread().getStackTrace();



回答5:


Guava could help. For example we want to see only first ten rows:

log.error("Error:", Joiner.on("\n").join(Iterables.limit(asList(ex.getStackTrace()), 10)));



回答6:


For an abbreviated version of e.printStackTrace():

        Exception e = ...
        System.out.println(e.toString());
        StackTraceElement[] elements = e.getStackTrace();
        for(int i = 0; i<elements.length && i < STACK_TRACE_LIMIT; i++) {
            System.out.println("\tat "+elements[i]);
        }

Replace STACK_TRACE_LIMIT with the limit you want or remove && i < STACK_TRACE_LIMIT to reproduce the output of a simple stack trace (e.g., no nested exceptions)

The innermost method calls are at index 0, main is at index length-1.



来源:https://stackoverflow.com/questions/21706722/fetch-only-first-n-lines-of-a-stack-trace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!