2014-02-25 261 views
29

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

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

任何想法如何实现这一功能?

编辑:

的ENV取代不为我工作:

standalone.conf

-DoauthLoginLogPath=/path/oauth2.log 

log44j2.xml

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

我可以看到wildfly安慰财产,我重新启动服务器,但我无法完成它。

回答

42

默认属性地图

看着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值的文件将首先在系统属性中查找,但如果失败,就会回落到财产定义在log4j2.xml配置文件顶部的Properties部分。

在线

的第二种方式是提供默认值在线:

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

一般来说,所有Log4j2查找遵循这个模式:${type:key:-defaultValue}

信封VS SYS

顺便说一句,在env前缀是环境变量(如Windows上的%PATH%),并没有涉及到sys,这是Java系统属性。另请参见http://logging.apache.org/log4j/2.x/manual/lookups.html

+0

它的工作原理正是您所描述的。谢谢。 –

+0

我不知道它是否在以前的版本中工作过,但这不起作用。您必须在属性中使用': - '来定义默认值。 – GoGoris

12

您可以使用相同的${sys:propName:-default}语法。注意': - ',它被称为“可变默认值分隔符”。对于“分隔符变量默认值”的默认值是:-,如庆典* nix中炮弹。

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

要使用相同的例子:

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

这对我来说非常合适。 – chaitanya

+0

不幸的是,似乎在加载log4j2.xml文件时解析了默认值。无法为例如设置默认值。通过线程上下文注入的变量。 – rec

+1

更正:有效,但必须添加第二个“$”,例如'$$ {ctx:username:-UNKNOWN}':) – rec