使用 Log4J 2 查找 JNDI 变量查找时如何设置默认值?

How do I set a default value when looking up a JNDI variable lookup with Log4J 2?

我已经使用 log4j2.xml 文件成功配置了 Log4J 2,并且我通过 JNDI variable lookup.

但是,如果 JNDI 变量不存在,我想为 Property 提供默认值。

这可能吗?

是的:这可以通过使用 默认 属性 映射来完成:

<Configuration status="DEBUG" name="Example">
    <Properties>
        <Property name="yourJndiVariableName">
            the value used if the JNDI variable cannot be found
        </Property>
    </Properties>

    ... more configuration ...

    <Loggers>
        <Root level="${jndi:yourJndiVariableName}">
            <AppenderRef ref="console"/>
        </Root>
    </Loggers>

    ... more configuration ...
</Configuration>

According to the Log4J 2 configuration documentation for property substitution,这也适用于其他 属性 来源(例如环境变量、系统属性等)。

试试这个:

<Root level="${jndi:yourJndiVariableName:-DEFAULT}">

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