SpringBoot中如何在Log4j2.xml中过滤Maven Profile值并配置环境变量
在Spring Boot项目中通过Maven Profile为Log4j2.xml注入环境变量
我之前刚好碰到过一模一样的需求——要把Maven Profile里的环境标识传递给Log4j2.xml,中间踩了个小坑,折腾了好一会儿才搞定,下面把完整的实现步骤和避坑点分享给你:
1. 先在pom.xml里给Profile配置专属属性
先区分不同环境的Profile,比如dev和生产环境,给每个Profile定义一个用于日志的环境变量:
<profiles> <profile> <id>dev</id> <activation> <property> <name>env</name> <value>dev</value> </property> </activation> <properties> <log.environment>DEV</log.environment> <!-- 这个属性会传给Log4j2 --> </properties> </profile> <profile> <id>prod</id> <activation> <property> <name>env</name> <value>prod</value> </property> </activation> <properties> <log.environment>PROD</log.environment> </properties> </profile> </profiles>
2. 配置Maven资源过滤,让变量能被替换
Spring Boot打包的时候默认不会自动替换资源文件里的Maven变量,所以得在pom.xml的build节点里开启资源过滤,指定要处理log4j2.xml:
<build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <!-- 开启过滤才能替换变量 --> <includes> <include>log4j2.xml</include> <!-- 只处理日志配置文件 --> </includes> </resource> <!-- 其他资源文件不需要过滤的话单独配置,避免影响 --> <resource> <directory>src/main/resources</directory> <filtering>false</filtering> <excludes> <exclude>log4j2.xml</exclude> </excludes> </resource> </resources> </build>
3. 在Log4j2.xml里引用Maven属性
这里要注意!一开始我直接用${log.environment},结果打包后变量根本没被替换,后来才知道Spring Boot资源过滤默认用@作为占位符(避免和Log4j自己的${}变量冲突),所以正确的写法是:
<PatternLayout> <Pattern>@log.environment@ - %d [%-6p] %c - %M - %m%n</Pattern> </PatternLayout>
如果你非要用${}的格式,也可以在pom.xml里修改资源过滤的分隔符:
<resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>log4j2.xml</include> </includes> <delimiters> <delimiter>${*}</delimiter> <!-- 把分隔符改成${} --> </delimiters> </resource>
这样就能在Log4j2.xml里用${log.environment}了,但个人还是推荐用@,省得和Log4j自身的系统变量搞混。
4. 打包时激活对应的Profile
最后打包的时候,要么直接指定Profile,要么通过系统属性激活:
# 方式1:直接用-P指定Profile mvn clean package -P dev # 方式2:用-D参数触发activation里的配置 mvn clean package -Denv=dev
这样打包出来的项目,日志里就会自动带上对应的环境标识啦!
内容的提问来源于stack exchange,提问作者Otávio
相关产品推荐
相关产品推荐

