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?
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:
This will tell you pretty much everything you need to know about where you've come from in the code.
You can use the
ex.getStackTrace()
to get the stack elements, theStackTraceElement
contains one line of the full stacks, then print print what ever you want.Guava could help. For example we want to see only first ten rows:
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:
Alternatively, use
e.getStackTrace()
to obtain aStackTraceElement[]
array. This gives you the caller stack (from inner to outer), but not the error message. You'll have to usee.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:This method displays
i
lines of the stack trace, skipping the first two.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