Log4j格式化:是否可以截断堆栈跟踪? [英] Log4j formatting: Is it possible to truncate stacktraces?
问题描述
我想在我的程序中只记录Exceptions的前几行。我知道,我可以做这样的事情只打印堆栈跟踪的前5行:
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());
}
但我宁愿使用log4j(或者更好地使用log4j上的slf4j)用于记录。有没有办法告诉log4j它应该只打印堆栈跟踪的前5行?
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?
推荐答案
你可以使用EnhancedPatternLayout在log4j中格式化堆栈跟踪。
You can use a EnhancedPatternLayout in log4j to format your stacktraces.
参见 http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/EnhancedPatternLayout.html ,特别是关于模式表中throwable模式的部分。
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.
请注意,对%throwable {n}
支持的支持相当新,至少需要log4j 1.2.16(这是撰写时的最新信息)
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)
出于跟踪目的,这是处理其实施的票证:
https://issues.apache.org/bugzilla/show_bug.cgi?id=48902
For tracking purposes, this is the ticket that dealt with its implementation: https://issues.apache.org/bugzilla/show_bug.cgi?id=48902
这篇关于Log4j格式化:是否可以截断堆栈跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!