41

This is my first foray into the world of LogBack, however I couldn't find anywhere in the documentation where I could define an encoder/pattern once and share it among multiple appenders. Any idea how to accomplish this?

Will Madison
  • 3,065
  • 2
  • 22
  • 19

2 Answers2

58

Patterns are reusable with variable substitution.

<configuration>

    <property name="defaultPattern"
        value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" />

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${defaultPattern}</pattern>
        </encoder>
    </appender>

    <root level="debug">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>
palacsint
  • 28,416
  • 10
  • 82
  • 109
33

For anyone interested I did find this little jewel from Chapter 4 of LogBack's documentation: "Each layout/encoder is associated with one and only one appender, referred to as the owning appender." which to me reads as though it's not possible for Appenders to share a single Encoder instance.

Will Madison
  • 3,065
  • 2
  • 22
  • 19
  • 1
    I've been programmatically creating appenders, encoders and layouts. I think the above is true: when I tried to share the encoders amongst appenders, I'd just end up having only one appender active (presumably because the encoder ended up only being attached to the last one I added it to). – Stuart Rossiter Mar 28 '13 at 08:18
  • 4
    Also this from the Configuration section: "Note that each appender has its own encoder. Encoders are usually not designed to be shared by multiple appenders. The same is true for layouts. As such, logback configuration files do not provide any syntactical means for sharing encoders or layouts." – Stuart Rossiter Mar 28 '13 at 08:20