Select only the first N lines of the stack trace

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

Code Layout:

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 calling method) without resetting the entire stack trace in the log or in order to rely on external libraries?

+5
source share
6 answers

I assume that you are asking that you have no exception for the solution. In this case, you can get the current stack trace:

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

This will tell you almost everything you need to know about where you came from in the code.

+8
source

ex.getStackTrace() , StackTraceElement , , .

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

i , .

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

- , traceCaller(). , .

@BrianAgnew (fooobar.com/questions/10773/...) StringWriter PrintWriter

+3

, StringWriter, , :

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

e.getStackTrace() StackTraceElement[]. ( ), . e.getMessage(), .

. . . log4j.

, Thread.currentThread():

Thread.currentThread().getStackTrace();
+2

. , :

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

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 with a STACK_TRACE_LIMITlimit or delete && < STACK_TRACE_LIMITto reproduce the output of a simple stack trace (for example, without nested exceptions)

The most internal method calls are at index 0, the main at index length-1.

0
source

All Articles