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?
To print a stack trace to log you Should declare logger and method info(e. toString()) or log(Level.INFO, e. toString()). Logging is the process of writing log messages during the execution of a program to get error and warning messages as well as info messages.
The printStackTrace() method of Java. lang. Throwable class used to print this Throwable along with other details like class name and line number where the exception occurred means its backtrace. This method prints a stack trace for this Throwable object on the standard error output stream.
A stack trace is generated whenever your app crashes because of an error or an exception. You can also print a stack trace at any point in your app code using methods such as Thread.
Accessing Stack Traces with the Thread Class You can obtain a stack trace from a thread – by calling the getStackTrace method on that Thread instance. This invocation returns an array of StackTraceElement, from which details about stack frames of the thread can be extracted.
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.
This might help you:
ch.qos.logback.classic.spi.ThrowableProxyUtil
StringBuffer sbuf = new StringBuffer();
....
IThrowableProxy throwbleProxy = event.getThrowableProxy();
if (throwbleProxy != null) {
String throwableStr = ThrowableProxyUtil.asString(throwbleProxy);
sbuf.append(throwableStr);
sbuf.append(CoreConstants.LINE_SEPARATOR);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With