B
B
BRONNER2014-09-25 14:10:20
XML
BRONNER, 2014-09-25 14:10:20

How to redefine variables in Logback.xml?

I flipped through the Logback documentation, found out that you can use conditions and variables, but I don’t know why they don’t work. I need the correct folder for logs to be selected depending on the OS

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <if condition='property("os.name").contains("windows")'>
        <then>
            <property name="app.dir" value="${env.APPDATA}" />
        </then>
    </if>
    <if condition='${os.name}.contains("mac")'>
        <then>
            <property name="app.dir" value="${user.home}/Library/Application Support" />
        </then>
    </if>
    <if condition='${os.name}.contains("linux")'>
        <then>
            <property name="app.dir" value="${user.home}" />
        </then>
    </if>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>${app.dir}/MyApp/logs/app.log</file>
        <encoder>
            <Pattern>[%d{Y-MM-dd HH:mm:ss}] [%level] %msg%n</Pattern>
        </encoder>
    </appender>
    <root level="INFO">
        <appender-ref ref="FILE"/>
    </root>
</configuration>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BRONNER, 2014-09-25
@BRONNER

I had to add more

<dependency>
  <groupId>org.codehaus.janino</groupId>
  <artifactId>janino</artifactId>
  <version>2.6.1</version>
</dependency>

I also simplified the code a bit.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <if condition='property("os.name").toLowerCase().startsWith("windows")'>
            <then>
                <file>${APPDATA}/MyApp/logs/MyApp.log</file>
            </then>
            <else>
                <if condition='property("os.name").toLowerCase().startsWith("mac")'>
                    <then>
                        <file>${user.home}/Library/Application Support/MyApp/logs/MyApp.log</file>
                    </then>
                    <else>
                        <file>${user.home}/.myapp/logs/myapp.log</file>
                    </else>
                </if>
            </else>
        </if>
        <encoder>
            <Pattern>[%d{Y-MM-dd HH:mm:ss}] [%level] %msg%n</Pattern>
        </encoder>
        <prudent>true</prudent>
    </appender>
    <root level="INFO">
        <appender-ref ref="FILE"/>
    </root>
</configuration>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question