Log4J 2属性替换-默认

lskq00tm  于 2023-11-18  发布在  其他
关注(0)|答案(2)|浏览(191)

我只是想知道是否有任何方法来提供默认值的属性替换在LOG4J?
我想在java系统属性中传递文件路径,然后将其与“${env:mySystemProperty}"一起使用。但是如果开发人员忘记设置此属性怎么办?那么我希望在log4j2.xml中定义一些有意义的默认值。
有没有想过如何实现这个功能?
编辑:
env替换对我不起作用:
standalone.conf

  1. -DoauthLoginLogPath=/path/oauth2.log

字符串
log4j2.xml

  1. <Appender type="File" name="File" fileName="${env:oauthLoginLogPath}" immediateFlush="true">
  2. <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。其形式如下:

  1. <Configuration status="debug">
  2. <Properties>
  3. <Property name="oauthLoginLogPath">default/location/of/oauth2.log</Property>
  4. </Properties>
  5. ...
  6. <Appenders>
  7. <Appender type="File" name="File" fileName="${sys:oauthLoginLogPath}">
  8. ....
  9. </Configuration

字符串
然后,如果您使用系统属性-DoauthLoginLogPath=/path/oauth2.log启动应用,则将首先在系统属性中查找File appender fileName值,但如果查找失败,则将回退到log4j2.xml配置文件顶部的Properties部分中定义的属性。

内联

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

  1. <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文档中阅读更多有关这方面的内容。
使用相同的示例:

  1. <Configuration status="debug">
  2. ...
  3. <Appenders>
  4. <Appender type="File" name="File"
  5. fileName="${sys:oauthLoginLogPath:-default/location/of/oauth2.log}">
  6. ....
  7. </Appenders>
  8. </Configuration>

字符串

相关问题