设置:
语言:Java
应用程序: Spring Boot 应用程序
项目: Maven
日志记录: Logback
容器:(开发用 Jetty | 生产用 Tomcat)
情况:
在我们的项目中,logback.xml 位于资源的根目录。该文件需要访问特定的应用程序属性。在下面的示例中,我们需要访问的属性是logging.home.dir,它将被存储为LOGGER_HOME。
示例:logback.xml
<configuration>
<property name="LOGGER_HOME" value="${logging.home.dir}" />
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOGGER_HOME}/application.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- other setting -->
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!-- other setting -->
</encoder>
</appender>
</configuration>
问题:
通常对于开发,可以使用默认应用程序属性文件application.properties 来保存所有必需的属性,但对于生产,此文件是外部化的。
发展
application.properties
logging.home.dir=temp/logs/
- 对于开发,只要
application.proerties 文件在类路径中可用,就可以使用 <property resource="application.properties" /> 在 logback.xml 中引用它
生产
Location: /opt/production/tc8-java8/my_wonderfull_app/application-prod.properties
application-prod.properties
logging.home.dir=application/logs/
- 此文件位于应用程序外部。不幸的是,由于该文件不在类路径中,我们无法像在开发中那样加载该文件。
解决方案:
要允许 logback 使用外部属性文件,您需要执行以下操作:
第 1 步: 启动应用程序时,您需要添加一个 VM 选项,指示加载外部属性文件的位置:
-Dmy.wonderful.app.external.properties.file=/opt/production/tc8-java8/my_wonderfull_app/application-prod.properties
第 2 步:您现在可以在 logback 文件中使用
<property file="${my.wonderful.app.external.properties.file}" /> <!-- note this MUST match the VM option name -->
<property name="LOGGER_HOME" value="${logging.home.dir}" /> <!-- property key from the file -->
简答:
应用虚拟机选项
-Dmy.wonderful.app.external.properties.file=/opt/production/tc8-java8/my_wonderfull_app/application-prod.properties
Logback.xml
my.wonderful.app.external.properties.file}" />
注意 1: 对于 Intellij,可以通过 Run/Debug Configuration > Spring Boot > [Configuration > Environment > ‘VM options:’] 添加 VM 选项
注意 2: 对于 Tomcat,可以在 /bin/setenv.sh 中添加 VM 选项
CATALINA_OPTS=-Dmy.wonderful.app.external.properties.file=/opt/production/tc8-java8/my_wonderfull_app/application-prod.properties