The encoder pattern in logback.xml
like
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
allows to enhance logging messages with context information like the current thread and the class name. Is there a possibility to display the identity hash code (returned by System.identityHashcode(Object)
) in the messages? I wouldn't mind a custom extension in form of a subclass, even though a configuration per class or package would be nice. I just have no idea where to start.
I'm aware that I can work around the problem by adding System.identityHashcode
to each log message. The idea for this question is to provide a configurable approach.
I'm accessing logback-classic
1.2.3 through SLF4J API 1.7.25, but wouldn't mind to upgrade to a 1.8.x snapshot.
Logback's
PatternLayout
containsdefaultConverterMap
which maps conversion words (%n
,%msg
,%d
etc) to implementations ofch.qos.logback.core.pattern.Converter
. This is what you referred to as:To include a hashCode in the log output you could provide your own implementation of
ch.qos.logback.core.pattern.Converter
and associate it with a custom conversion word as follows ...Add this to
logback.xml
Implement
some.package.HashCodeConverter
as follows:Update your encoder pattern to use the conversion word
hc
:With these changes in place your custom converter will be engaged and the output will look like this ...
Where
1847637306
is the hashCode for the class which emitted the log event.Notes:
HashCodeConverter