根据 docs ,应该可以使用
SpringProfile
仲裁器根据活动的 Spring Boot 配置文件来选择是否包含给定的“节点”;所以我认为这应该可行:
<Properties>
<SpringProfile name="dev">
<Property name="logdir" value="/tmp/log"/>
</SpringProfile>
<SpringProfile name="docker">
<Property name="logdir" value="/var/log"/>
</SpringProfile>
<Property name="logfile" value="users.log"/>
</Properties>
但是,这似乎没有按预期配置属性(根本)(尽管,在我配置的不同部分,这有效):
<Loggers>
<!-- LOG everything at INFO level, unless the `debug` Spring Profile is used -->
<SpringProfile name="debug">
<Root level="debug">
<AppenderRef ref="Console"/>
<AppenderRef ref="RollingFile"/>
</Root>
</SpringProfile>
<SpringProfile name="!debug">
<Root level="info">
<AppenderRef ref="Console"/>
<AppenderRef ref="RollingFile"/>
</Root>
</SpringProfile>
</Loggers>
我的猜测是,要么(a)我在
Properties
中做错了,要么(b)不知何故,Properties
节点不受SpringProfile仲裁器的影响。
我知道我可以复制所有
Appender
配置以使其执行我想要的操作(或就此而言使用不同的文件);但看起来...好吧,浪费了 - 我想要的只是基于 Spring Profile 的日志的不同目录。
请注意,我知道可以通过其他方式实现这一目标的所有可能的奇怪而美妙的方式;在这里,我只感兴趣是否可以通过
Property
仲裁器影响 Log4j SpringProfile
的值 - 非常感谢您的任何建议!
您可以在
SpringProfile
节点内自由使用 <Properties>
,但您需要记住,log4j2.xml
配置文件在 Spring Boot 应用程序的生命周期中会使用两次:
Environment
可用,并且 ${logdir}
扩展为 ${logdir}
,ApplicationEnvironmentPreparedEvent
事件,Spring Boot 就会再次重新配置 Log4j Core。从这一刻起${logdir}
将正常扩展。因此您还需要为
logdir
设置一个将在初始阶段使用的值。由于问题#1783,最干净的解决方案不起作用:
<Select>
<SpringProfile name="dev">
<Property name="logdir" value="/tmp/log"/>
</SpringProfile>
<SpringProfile name="docker">
<Property name="logdir" value="/var/log"/>
</SpringProfile>
<DefaultArbiter>
<Property name="logdir" value="..."/>
</DefaultArbiter>
</Select>
但作为解决方法,您可以使用:
<Property name="logdir" value="..."/>
<SpringProfile name="dev">
<Property name="logdir" value="/tmp/log"/>
</SpringProfile>
<SpringProfile name="docker">
<Property name="logdir" value="/var/log"/>
</SpringProfile>
并忽略错误消息。
备注:也可以切换两个配置文件:
log4j2.xml
用于应用程序的启动阶段(不允许使用 SpringProfile
),log4j2-spring.xml
用于应用程序的运行时阶段。