简体   繁体   中英

Spring Boot 2.1.2 : How to pass values from application.properties to log4j2.xml?

Basically I want to dynamically pass the log folder path. (Requirement is to pass the log folder path from command line as arguments when I run the spring boot jar). Below is my log4j2.xml for reference.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} %p %m%n</Property>
        <Property name="APP_LOG_ROOT">logs</Property>
    </Properties>
    <Appenders>
        <Console name="Console" follow="true" target="SYSTEM_OUT">
            <PatternLayout pattern="${LOG_PATTERN}" />
        </Console> 
        <RollingFile name="appLog"
            fileName="${APP_LOG_ROOT}/application.log"
            filePattern="${APP_LOG_ROOT}/application-%d{yyyy-MM-dd}-%i.log">
            <PatternLayout pattern="${LOG_PATTERN}" />
            <Policies>
                <SizeBasedTriggeringPolicy size="20KB" />
            </Policies>
            <DefaultRolloverStrategy max="10" />
        </RollingFile>
    </Appenders>
    <Loggers>
         <Logger name="com.test" additivity="false" level="ERROR">
            <AppenderRef ref="Console" />
        </Logger> 
        <Logger name="com.test" additivity="false" level="ALL">
            <AppenderRef ref="appLog" />
        </Logger>
        <Root level="ALL">
             <AppenderRef ref="appLog" />
        </Root>
    </Loggers>
</Configuration>

Command line: You can pass values with -D and with the name of variable.

mvn spring-boot:run -DAPP_LOG_ROOT=/somepath/

you can find more details here https://maven.apache.org/ref/3.6.0/maven-embedder/cli.html

and dont forget to change your xml. I havent tested below but you can figure out.

<Property name="APP_LOG_ROOT">${APP_LOG_ROOT:${APP_LOG_ROOT:./logs}}</Property>

application:properties: as long as your xml accepting APP_LOG_ROOT as above. probably just adding

APP_LOG_ROOT=/sompath

will be enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM