8

I am new to Logback, I am trying to add file path dynamically, with a property file, for both windows and Linux.

Here is the code sinppet I have, how can I get the value to ${MY_HOME}

<appender name="SERVER_FILE" class="ch.qos.logback.core.FileAppender">
    <file>${MY_HOME}/server.log</file>
    <append>true</append>
    <encoder>
      <pattern>%d [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
  </appender> 
user2108383
  • 239
  • 1
  • 9
  • 22

1 Answers1

9

Typically this is a system property, there are some answers that touch on this but only provide one part of the answer. These are:

But the manual on configuration shows that the mechanism is quite flexible

As in many scripting languages, logback configuration files support definition and substitution of variables. Variables can be defined within the configuration file itself, in an external file, in an external resource or even computed and defined on the fly.

In summary you have a number of options for defining the value of MY_HOME:

In the file

You are able to define the value in the file itself with:

<property name="MY_HOME" value="/home/myhome"/>

In the system properties

You can arrange for it to be set as a system property, most likely when you start the JVM.

java -DMY_HOME="/home/myhome" ...

From a property file on your system

You can arrange for logback to read a property file:

<property file="/opt/example/instance_1/properties/system.properties" />

From the classpath

You can write a properties file into a resources directory or into a jar and read it out as a resource, using the classpath.

<property resource="prod.properties" />

Using the property definer

You can arrange to call into your code, by using a property definer. For example:

<define name="MY_HOME" class="biz.nowhere.HomePropertyDefiner">
   <application>app</application>
</define>

Where that class is something like (as an example):

public class HomePropertyDefiner extends PropertyDefinerBase {

  private String application;

  @Override
  public String getPropertyValue() {
    return String.format("/opt/%s/%s", application, MyInstanceManager.instancePath());
  }

  public void setApplication(String application) {
      this.application = application;
  }

}
Community
  • 1
  • 1
andygavin
  • 2,784
  • 22
  • 32
  • I had some inconsistent `ch.qos.logback.core.util.IncompatibleClassException` issue with `ch.qos.logback.core.PropertyDefinerBase` had to replace `extends PropertyDefinerBase` with `extends ch.qos.logback.core.spi.ContextAwareBase implements ch.qos.logback.core.spi.PropertyDefiner` – Anand Rockzz Jun 21 '18 at 20:19