Skip to content
Advertisement

How to make path location dynamic in xml

I have a logback.xml configured in a spring MVC + hibernate project, it is working fine on my local machine. the local machine has windows 10 OS installed.

I wish to run the code of production machine which has Linux installed.

What is want to know, is there a way to make LOG_PATH and LOG_ARCHIVE locations dynamic according to OS ? So that when the code is deployed on production machine I would not have to manually change the the path locations.

Any help is appreciated, Let me know if anything else is needed. Thank you in advance. 😀

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true" scan="true" scanPeriod="30 seconds">
    <property name="LOG_PATH" value="D:/coinLogs" />
    <property name="LOG_ARCHIVE" value="${LOG_PATH}/archive" />

    <appender name="Console-Appender" class="ch.qos.logback.core.ConsoleAppender">
        <layout>
            <pattern>[%d{yyyy-MM-dd HH:mm:ss}] - [%X{requestId}] - %p %c -- %m%n</pattern>
        </layout>
    </appender>

    <appender name="File-Appender" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_PATH}/logfile.log</file>
        <encoder>
            <pattern>[%d{yyyy-MM-dd HH:mm:ss}] - [%X{requestId}] - %p %c -- %m%n
            </pattern>
            <outputPatternAsHeader>true</outputPatternAsHeader>
        </encoder>

        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- rollover daily -->
            <fileNamePattern>${LOG_ARCHIVE}/rollingfile.log.%d{yyyy-MM-dd}.log
            </fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                        <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>


    <logger name="coinPay.logbackxml" level="info" additivity="false">
        <appender-ref ref="Console-Appender" />
        <appender-ref ref="File-Appender" />
    </logger>

    <!-- To remove extra hibernate logs -->
    <logger name="org.hibernate">
        <level value="info" />
    </logger>

    <root>
        <appender-ref ref="Console-Appender" />
        <appender-ref ref="File-Appender" />
    </root>

</configuration>

Advertisement

Answer

You can create the logback file in an external location and pass it as a param while starting the app as shown below.

java -Dlogback.configurationFile=path/logback.xml MyApp

Adding the following configuration to the logback.xml will scan the file every 30 seconds for any changes. If a change is detected it will reconfigure the log settings.

<configuration scan="true" scanPeriod="30 seconds" > 
  ...
</configuration>

Now if you want to change anything you can directly change it in logback.xml

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement