Log4J 2属性替换-默认

lskq00tm  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(129)

我只是想知道是否有任何方法来提供默认值的属性替换在LOG4J?
我想在java系统属性中传递文件路径,然后将其与“${env:mySystemProperty}"一起使用。但是如果开发人员忘记设置此属性怎么办?那么我希望在log4j2.xml中定义一些有意义的默认值。
有没有想过如何实现这个功能?
编辑:
env替换对我不起作用:
standalone.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控制台的属性,我重新启动服务器,但我不能得到它完成。

eivnm1vs

eivnm1vs1#

默认属性Map

查看http://logging.apache.org/log4j/2.x/manual/configuration.html#PropertySubstitution,您可以在配置文件中指定默认属性Map。其形式如下:

<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启动应用,则将首先在系统属性中查找File appender fileName值,但如果查找失败,则将回退到log4j2.xml配置文件顶部的Properties部分中定义的属性。

内联

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

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


通常,所有Log4j2查找都遵循以下模式:${type:key:-defaultValue}

环境vs系统

顺便说一下,env前缀是用于环境变量(如Windows上的%PATH%),与sys无关,后者是Java系统属性。

vtwuwzda

vtwuwzda2#

你可以使用相同的${sys:propName:-default}语法。注意':-',它被称为“variable default value "。“variable default value”的 default 值是:-,就像在 bash 和其他**nix shell中一样。
您可以在StrSubstitutor类的Log4j 2文档中阅读更多有关这方面的内容。
使用相同的示例:

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

字符串

相关问题