Get the file name from complete path in log4j2 xml

2019-12-16 18:43发布

问题:

In my log4j2.xml file, I get the complete path of the logfile by passing a system property

-Dlogfilename=/home/user/logs/server

Log4j2 configuration:

<Property name="logFile">${sys:logfilename:-/home/user/logs/server}</Property>

As an added requirement, I need to get the name of the log file from the above property and I cannot pass a new system property. How can I get just the name of the file from the complete path? I dont have any experience with XML other than its use for data transport.

回答1:

You're using the System Properties Lookup incorrectly. You should specify the lookup and the key you wish to look up like this: ${sys:logfilename}

Here's a simple example:

package example;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class SomeClass {

    private static final Logger log = LogManager.getLogger();

    public static void main(String[] args){
        log.info("Here's some info!");
    }
}

Here is the log4j2.xml config file:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <File name="File" fileName="logs/${sys:myProperty}"
            immediateFlush="false" append="false">
            <PatternLayout
                pattern="%-5level %logger{36} - %msg%n" />
        </File>
    </Appenders>

    <Loggers>
        <Root level="debug">
            <AppenderRef ref="File"  />
        </Root>
    </Loggers>
</Configuration>

When I run this code with the following JVM parameter:

-DmyProperty=myFile.log

it generates a file with the name "myFile.log" and the file contains the following output:

INFO  example.SomeClass - Here's some info!