propertieslogback

Must multiple Logback PropertyDefiner implementations be created to pull in multiple properties?


I am able to use a Logback PropertyDefiner to access a single property from a logback.xml configuration file. If I have 3 properties to access, I am currently using 3 separate implementations of PropertyDefiner (one for each property).

Is there a way to access multiple properties from a single PropertyDefiner implementation? Or perhaps there is another interface that supports multiple properties?

I want to be be able to use properties to plugin different values, based on environment (dev, ist, uat, perf, prod) for various logging configurations (context name, log levels, appender file names, file sizes, etc.).

I found this question, which is similar, but did not answer the question of how to access multiple properties.


Solution

  • Create a PropertyDefiner implementation class. The PropertyDefinerBase implementation is already provided.

        package foo.bar;
    
        import java.util.HashMap;
        import java.util.Map;
        
        import ch.qos.logback.core.PropertyDefinerBase;
        
        public class LoggingPropertiesDefiner extends PropertyDefinerBase {
        
          private static Map<String, String> properties = new HashMap<>();
        
          static {
            properties.put("encoderPattern", "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %message%n");
            properties.put("maxFileSize", "50MB");
            properties.put("rootLogLevel", "INFO");
          }
        
          private String propertyLookupKey;
        
          public void setPropertyLookupKey(String propertyLookupKey) {
            this.propertyLookupKey = propertyLookupKey;
          }
        
          @Override
          public String getPropertyValue() {
            //TODO In the real world, get properties from a properties loader.
            return properties.get(propertyLookupKey);
          }
        }
    

    In the logback.xml, use the same PropertyDefiner class for each property. Provide a different lookup key for each:

        <define name="encoderPattern" class="foo.bar.LoggingPropertiesDefiner">
            <propertyLookupKey>encoderPattern</propertyLookupKey>
        </define>
    
        <define name="maxFileSize" class="foo.bar.LoggingPropertiesDefiner">
            <propertyLookupKey>maxFileSize</propertyLookupKey>
        </define>
    
        <define name="rootLogLevel" class="foo.bar.LoggingPropertiesDefiner">
            <propertyLookupKey>rootLogLevel</propertyLookupKey>
        </define>
    

    Reference the property names in the logback.xml:

        <root level="${rootLogLevel}">
            <appender-ref ref="FILE"/>
        </root>