Search code examples
stack-tracelogback

How to print stack trace from logback custom layout?


I'm writing a CustomLayout for logback, because I want to tweak thread names and logger names. The logback documentation says

In the above example, the doLayout method ignores any eventual exceptions contained in the event. In a real world layout implementation, you would most probably want to print the contents of exceptions as well.

Umm, yes, of course I want to print stack traces when the default implementation would. But I can't find any instructions for doing so. I downloaded the sources and looked around. The following seems to work:

/**
 * 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();
}

Is there a better/more approved way?


Solution

  • ThrowableProxyConverter is the way to go to print the stack trace. Thus, the code you intend to use looks good. However, instead of writing a CustomLayout, you could adapt PatternLayout with custom converters. In the vast majority of cases, that is the easier/better option.