问题描述
我只是想知道是否有办法为LOG4J中的属性替换提供默认值?
I just wonder if there is any way to provide default value for property substitution in LOG4J?
我想在java系统属性中传递文件路径然后使用它使用$ {env:mySystemProperty}。但是如果开发人员忘记设置此属性呢?然后我想在log4j2.xml中定义一些有意义的默认值。
I want to pass file path in java system property and then use it with "${env:mySystemProperty}". But what if developer forgets to set this property? Then I would like to have some meaningful default value defined in log4j2.xml.
知道如何实现这个功能吗?
Any idea how to achieve this functionality?
编辑:
env替换对我不起作用:
The env substitution does not work for me:
standalone.conf
standalone.conf
-DoauthLoginLogPath=/path/oauth2.log
log44j2.xml
log44j2.xml
<Appender type="File" name="File" fileName="${env:oauthLoginLogPath}" immediateFlush="true">
<Appender type="File" name="File" fileName="${sys:oauthLoginLogPath}" immediateFlush="true">
我可以在wildfly控制台中看到该属性,我重新启动了服务器,但我无法完成它。
I can see in wildfly console the property, I restarted server but I cannot get it done.
推荐答案
默认物业地图
望着
您可以在配置文件中指定默认属性映射。采用以下形式:
Looking at http://logging.apache.org/log4j/2.x/manual/configuration.html#PropertySubstitutionyou can specify a default property map in the configuration file. That takes this form:
<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配置文件顶部的属性
部分中定义的属性。
Then, if you start your app with system property -DoauthLoginLogPath=/path/oauth2.log
, the File appender fileName
value will first be looked up in system properties, but if that fails, it will fall back to the property defined in the Properties
section at the top of the log4j2.xml configuration file.
内联
第二种方法是提供内联默认值:
A second way is to provide the default value inline:
<Appender type="File" name="File" fileName="${sys:oauthLoginLogPath:-default/location/of/oauth2.log}">
通常所有Log4j2查找都遵循以下模式: $ {type:key: - defaultValue}
。
Generally all Log4j2 lookups follow this pattern: ${type:key:-defaultValue}
.
Env vs sys
顺便说一句, env
前缀适用于环境变量(如Windows上的%PATH%),与 sys ,这是Java系统属性。另请参见
By the way, the
env
prefix is for environment variables (like %PATH% on Windows), and is not related to sys
, which is Java system properties. See also http://logging.apache.org/log4j/2.x/manual/lookups.html
这篇关于Log4J2属性替换 - 默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!