如何从logback自定义布局打印堆栈跟踪?

问题描述 投票:8回答:2

我正在编写一个CustomLayout用于logback,因为我想调整线程名称和记录器名称。 logback文档说

在上面的示例中,doLayout方法忽略事件中包含的任何最终异常。在现实世界的布局实现中,您很可能也想要打印异常的内容。

嗯,是的,当然我想在默认实现时打印堆栈跟踪。但我找不到任何指示。我下载了源代码并环顾四周。以下似乎有效:

/**
 * How much stack to print if there's an exception.
 */
private List<String> stackOptionList = Arrays.asList("full");

@Override
public String doLayout(ILoggingEvent event) {
  StringBuffer sbuf = new StringBuffer(128);
  . . .
  IThrowableProxy proxy = event.getThrowableProxy();
  if (proxy != null) {      
    ThrowableProxyConverter converter = new ThrowableProxyConverter();
    converter.setOptionList(stackOptionList);
    converter.start();
    sbuf.append(converter.convert(event));
    sbuf.append(CoreConstants.LINE_SEPARATOR);
  }
  . . .
  return sbuf.toString();
}

有更好/更批准的方式吗?

stack-trace logback
2个回答
7
投票

ThrowableProxyConverter是打印堆栈跟踪的方法。因此,您打算使用的代码看起来不错。但是,您可以使用custom converters调整PatternLayout,而不是编写CustomLayout。在绝大多数情况下,这是更容易/更好的选择。


2
投票

这可能对您有所帮助:

ch.qos.logback.classic.spi.ThrowableProxyUtil

StringBuffer sbuf = new StringBuffer(128);
....
IThrowableProxy throwbleProxy =  event.getThrowableProxy();
if (throwbleProxy != null) {
    String throwableStr = ThrowableProxyUtil.asString(throwbleProxy);
    sbuf.append(throwableStr);
    sbuf.append(CoreConstants.LINE_SEPARATOR);
}
© www.soinside.com 2019 - 2024. All rights reserved.