try a makeover
First take the chapter4-2-2 project as the basic project, let's carry out the transformation of the multi-environment configuration.
- Create a multi-environment configuration file
application-dev.properties
: Development environmentapplication-test.properties
:test environmentapplication-prod.properties
:Production Environment
application.properties
Add properties in:spring.profiles.active=dev
(default activeapplication-dev.properties
configuration)application-dev.properties
andapplication-test.properties
add the log level definition in the config file:logging.level.com.didispace=DEBUG
application-prod.properties
Add the log level definition to the configuration file:logging.level.com.didispace=INFO
Through the above definition, logging.level.com.didispace
different levels are defined in the configuration files of different environments, but we have already handed over the log to log4j management, let's see the log definition under the com.didispace package in our log4j.properties is like this, Fixed DEBUG level defined and output to an appender named didifile definition.
# LOG4J配置
log4j.category.com.didispace=DEBUG, didifile
# com.didispace下的日志输出
log4j.appender.didifile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.didifile.file=logs/my.log
log4j.appender.didifile.DatePattern='.'yyyy-MM-dd
log4j.appender.didifile.layout=org.apache.log4j.PatternLayout
log4j.appender.didifile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L ---- %m%n
So, how to dynamically change this DEBUG level? References to parameters in the configuration file are also mentioned in "Spring Boot Property Configuration File Details" . We need to replace DEBUG with application-{profile}.properties
the definition in the configuration file logging.level.com.didispace
, so the configuration becomes the following:
# LOG4J配置
log4j.category.com.didispace=${logging.level.com.didispace}, didifile
# com.didispace下的日志输出
log4j.appender.didifile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.didifile.file=logs/my.log
log4j.appender.didifile.DatePattern='.'yyyy-MM-dd
log4j.appender.didifile.layout=org.apache.log4j.PatternLayout
log4j.appender.didifile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L ---- %m%n
At this point we have completed all the configuration work, we can run the unit test and see the log content output in the my.log file. By modifying the default application-dev.properties
configuration log level to INFO, and then running the unit test DEBUG content is output to my.log to verify whether the parameters are correctly referenced.
For users of different environments, there is no need to change the code or package files, and only need to add parameters to the execution command. For example, if I want to use the level of the production environment, then I can run the application like this:
java -jar xxx.jar --spring.profiles.active=prod