Log4j 格式:是否可以截断堆栈跟踪? [英] Log4j formatting: Is it possible to truncate stacktraces?
问题描述
我只想记录程序中异常的前几行.我知道,我可以做这样的事情来只打印堆栈跟踪的前 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(或 slf4j 而不是 log4j 更准确)进行日志记录.有没有办法告诉 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?
推荐答案
您可以在 log4j 中使用 EnhancedPatternLayout 来格式化堆栈跟踪.
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屋!