Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
215 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...