Log4J2 属性替换 - 默认

2024-01-31

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

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

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

EDIT:

env 替换对我不起作用:

独立配置文件

-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 控制台中看到该属性,我重新启动了服务器,但无法完成它。


默认属性图

看着http://logging.apache.org/log4j/2.x/manual/configuration.html#PropertySubstitution 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值将首先在系统属性中查找,但如果失败,它将回退到系统属性中定义的属性Propertieslog4j2.xml 配置文件顶部的部分。

Inline

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

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

一般来说,所有 Log4j2 查找都遵循以下模式:${type:key:-defaultValue}.

环境与系统

顺便说一句,env前缀用于环境变量(如 Windows 上的 %PATH%),与sys,这是 Java 系统属性。也可以看看http://logging.apache.org/log4j/2.x/manual/lookups.html http://logging.apache.org/log4j/2.x/manual/lookups.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Log4J2 属性替换 - 默认 的相关文章

随机推荐