Get the file name from complete path in log4j2 xml

独自空忆成欢 提交于 2020-01-07 08:35:33

问题


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!


来源:https://stackoverflow.com/questions/52402895/get-the-file-name-from-complete-path-in-log4j2-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!