Log4J2 属性替换 - 默认

问题描述 投票:0回答:2

我只是想知道是否有任何方法可以为LOG4J中的属性替换提供默认值?

我想在java系统属性中传递文件路径,然后将其与“${env:mySystemProperty}”一起使用。但是如果开发者忘记设置这个属性怎么办?然后我想在 log4j2.xml 中定义一些有意义的默认值。

知道如何实现这个功能吗?

编辑:

环境替换对我不起作用:

独立.conf

-DoauthLoginLogPath=/path/oauth2.log

log4j2.xml

<Appender type="File" name="File" fileName="${env:oauthLoginLogPath}" immediateFlush="true">
<Appender type="File" name="File" fileName="${sys:oauthLoginLogPath}" immediateFlush="true">

我可以在 Wildfly 控制台中看到该属性,我重新启动了服务器,但无法完成它。

java logging log4j log4j2
2个回答
88
投票

默认属性图

查看 http://logging.apache.org/log4j/2.x/manual/configuration.html#PropertySubstitution 您可以在配置文件中指定默认属性映射。采用这种形式:

<Configuration status="debug">
  <Properties>
    <Property name="oauthLoginLogPath">default/location/of/oauth2.log</Property>
  </Properties>
  ...
  <Appenders>
    <Appender type="File" name="File" fileName="${sys:oauthLoginLogPath}">
    ....
</Configuration

然后,如果您使用系统属性

-DoauthLoginLogPath=/path/oauth2.log
启动应用程序,将首先在系统属性中查找文件附加器
fileName
值,但如果失败,它将回退到
Properties
部分中定义的属性在 log4j2.xml 配置文件的顶部。

内联

第二种方法是内联提供默认值:

<Appender type="File" name="File" fileName="${sys:oauthLoginLogPath:-default/location/of/oauth2.log}">

一般来说,所有 Log4j2 查找都遵循以下模式:

${type:key:-defaultValue}

环境与系统

顺便说一句,

env
前缀用于环境变量(如Windows上的%PATH%),与Java系统属性
sys
无关。另请参阅 http://logging.apache.org/log4j/2.x/manual/lookups.html


22
投票

您可以使用相同的

${sys:propName:-default}
语法。注意':-',它被称为“变量默认值分隔符”。 “变量默认值分隔符”的 default 值为
:-
,如 bash 和其他 *nix shell 中一样。

您可以在 Log4j 2 文档中了解有关 StrSubstitutor 类的更多信息。

使用相同的示例:

<Configuration status="debug">
  ...
    <Appenders>
        <Appender type="File" name="File"
                  fileName="${sys:oauthLoginLogPath:-default/location/of/oauth2.log}">
        ....
    </Appenders>
</Configuration>
© www.soinside.com 2019 - 2024. All rights reserved.