Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

java - Log4j formatting: Is it possible to truncate stacktraces?

I want to log only the first few lines of Exceptions in my program. I know, I can do something like this to print only the first 5 lines of a stacktrace:

Throwable e = ...;
StackTraceElement[] stack = e.getStackTrace();
int maxLines = (stack.length > 4) ? 5 : stack.length;
for (int n = 0; n < maxLines; n++) {
    System.err.println(stack[n].toString());
}

But I would rather use log4j (or slf4j over log4j to be more precise) for logging. Is there a way to tell log4j that it should only print the first 5 lines of a stacktrace?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a EnhancedPatternLayout in log4j to format your stacktraces.

See http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/EnhancedPatternLayout.html, specifically the section about the "throwable" pattern in the pattern table.

Note that support for the %throwable{n} support is rather new and requires at least log4j 1.2.16 (which is the latest at time of writing)

For tracking purposes, this is the ticket that dealt with its implementation: https://issues.apache.org/bugzilla/show_bug.cgi?id=48902


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...