Marnes Marnes - 3 months ago 12
Java Question

Slf4j/logback - print stacktrace in separate file

I'm setting up a project with slf4j backed by logback. I log exceptions at the root of my program with

logger.error(ex.getMessage(), ex);


I've got logback configured like so (minus unimportant stuff)

<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>app.log</file>
<encoder>
<pattern>${details}: %msg%n</pattern>
</encoder>
</appender>

<root>
<appender-ref ref="FILE"/>
</root>


The important bits are working fine. My problem is that despite %ex not being included in my pattern, stacktraces get printed anyway, as regular sysout-like lines, after the error message.

00:23:50.713 ERROR blabla: something happened
java.lang.RuntimeException: something happened
at ...
at ...


Since I want my log to be easily parsable, that stacktrace is in my way (it doesn't fit into my line format) and I don't want it there. I want stacktraces to go to a separate file, printed as

<file>stacktrace.log</file>
<encoder>
<pattern>${details}: %ex%n</pattern>
</encoder>


I'd assume something this obvious isn't a bug in logback where stacktraces oopsie their way into the output despite being absent in the pattern. I've been going over the documentation but I can't seem to find a way to get what I want: to print stacktraces only in a dedicated stacktrace log. Can it be done?

Answer

I just found this important nuance in the documentation:

If you do not specify %xThrowable or another throwable-related conversion word in the conversion pattern, PatternLayout will automatically add it as the last conversion word, on account of the importance of stack trace information. The $nopex conversion word can be substituted for %xThrowable, if you do not wish stack trace information to be displayed. See also the %nopex conversion word.

With this in mind, it's just simple filtering on the presence of an exception and such.

Comments