使用Main Arguments Lookup(Application)替换log4j2属性



我正在尝试跟踪-

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

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

我的主要课程看起来像

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
}

它运行一个论点

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

我想要我的日志文件名为Application1.log

Log4j2.xml看起来像-

<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>

但不知何故,这里没有发生替换,我的日志文件被创建为名称-e.log,而不是Application1.log

11:41:36.293〔main〕INFO Runner-日志文件的位置是:-e.Log

我试着给

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

但这给了我错误-

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

我看到了一个类似的问题——Log4j2系统属性被写为文件

但不知怎么的,这对我不起作用。

任何建议都将不胜感激。

诚挚的问候,

在Log4j2中,:-分隔符用于提供默认值。您引用的文档中对其进行了描述:

注意:许多应用程序使用前导短划线来标识命令参数。指定CCD_ 2将导致查找失败;主";默认值为"0"-文件";。为了避免这种情况"在${main:--file}中,将查找名称与关键字分隔开后必须跟一个反斜杠作为转义符。

因此,只需将${main:--e}替换为${main:--e},它就可以工作了。

最新更新