Fetch only first N lines of a Stack Trace

22,813

Solution 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.

Solution 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]);

Solution 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

Solution 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();

Solution 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)));
Share:
22,813
Mindwin
Author by

Mindwin

Updated on July 15, 2021

Comments

  • Mindwin
    Mindwin almost 3 years

    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?