简体   繁体   中英

log4j2 property substitution using Main Arguments Lookup (Application)

I am trying to follow -

https://logging.apache.org/log4j/2.x/manual/configuration.html#PropertySubstitution

https://logging.apache.org/log4j/2.x/manual/lookups.html#AppMainArgsLookup

My main class looks like -

 public static void main(String[] args) throws IOException {
    
--Some Code
    MyappArgs jArgs=new MyappArgs();
            JCommander MyappCmd=JCommander.newBuilder()
                    .addObject(jArgs)
                    .build();
            MyappCmd.parse(args);
            MainMapLookup.setMainArguments(args);
--Some code
    }

It runs it an argument

java -jar MyApp.jar --e "appllication1" 

I want name of my log file as Application1.log

Log4j2.xml looks like -

<RollingFile name="RollingFile" fileName="${main:--e}.log" filePattern="${main:--e}.log">
            <Policies>
                <OnStartupTriggeringPolicy/>
            </Policies>
            <DefaultRolloverStrategy fileIndex="max" max="10"/>
            <PatternLayout pattern="[%d{dd/MMM/yyyy HH:mm:ss.SSS}]> %-5p - %m%n"/>
        </RollingFile>

But somehow substition is not happening here, my log file gets created with name -e.log instead of Application1.log

11:41:36.293 [main] INFO Runner - Location of Log files is: -e.log

I tried to give -

<RollingFile name="RollingFile" fileName="${main:1}.log" filePattern="${main:1}.log">

But this gave me error -

main ERROR Unable to create file ${main:1}.log java.io.IOException: The filename, directory name, or volume label syntax is incorrect

I see a similar question - Log4j2 system property written as a file

But somehow this is not working for me.

Any pointers are appreciated.

Kind Regards,

A

In Log4j2 the :- separator is used to provide default values. It is described in the documentation you cite :

Note: Many applications use leading dashes to identify command arguments. Specifying ${main:--file} would result in the lookup failing because it would look for a variable named "main" with a default value of "-file". To avoid this the ":" separating the Lookup name from the key must be followed by a backslash as an escape character as in ${main:\--file} .

Hence just replace ${main:--e} with ${main:\--e} and it should work.

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