Spring boot 如何在SpringBootTest中为logback设置环境变量?
如何为SpringBootTest设置环境变量以进行logback配置?Spring boot 如何在SpringBootTest中为logback设置环境变量?,spring-boot,environment-variables,logback,spring-boot-test,Spring Boot,Environment Variables,Logback,Spring Boot Test,如何为SpringBootTest设置环境变量以进行logback配置? 在Logback.xml中使用环境变量时发生Logback配置错误 在logback.xml中 <appender name="plainLogsToFile" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>/${LOG_PATH}/service.log</file
在Logback.xml中使用环境变量时发生Logback配置错误 在logback.xml中
<appender name="plainLogsToFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>/${LOG_PATH}/service.log</file>
报告了以下例外情况:
openFile(/LOG_PATH_IS_UNDEFINED/service.log,true) call failed. java.io.FileNotFoundException: /LOG_PATH_IS_UNDEFINED/service.log (No such file or directory)
at org.springframework.boot.logging.logback.LogbackLoggingSystem.loadConfiguration(LogbackLoggingSystem.java:162)
at org.springframework.boot.logging.logback.LogbackLoggingSystem.reinitialize(LogbackLoggingSystem.java:208)
at org.springframework.boot.logging.AbstractLoggingSystem.initializeWithConventions(AbstractLoggingSystem.java:74)
at org.springframework.boot.logging.AbstractLoggingSystem.initialize(AbstractLoggingSystem.java:59)
at org.springframework.boot.logging.logback.LogbackLoggingSystem.initialize(LogbackLoggingSystem.java:115)
at org.springframework.boot.logging.LoggingApplicationListener.initializeSystem(LoggingApplicationListener.java:303)
at org.springframework.boot.logging.LoggingApplicationListener.initialize(LoggingApplicationListener.java:276)
at org.springframework.boot.logging.LoggingApplicationListener.onApplicationEnvironmentPreparedEvent(LoggingApplicationListener.java:239)
at org.springframework.boot.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:212)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
我使用@TestPropertySource,@ActiveProfiles(“test”),@springbootest(…,properties={})来显式设置属性值。
但是,logback只涉及系统环境变量。
我只关心测试执行。
一些忽略回写的方法也值得赞赏。在之前使用
@、@之前使用
或静态
代码块来为回写配置这些变量太晚了
您可以通过自定义JUnit 5扩展来解决此问题:
public class PropertyExtension implements BeforeAllCallback {
@Override
public void beforeAll(ExtensionContext context) {
System.out.println("Setting system property");
System.setProperty("LOG_PATH", "/my/logpath/for/testing");
}
}
并在测试中使用它,如:
@ExtendWith(PropertyExtension.class)
@SpringBootTest(classes = Application.class)
public class MyTestClass {
}
使用JUnit4,您可以通过自定义类规则
实现同样的功能。阅读更多关于这方面的内容
此外,您还可以为这些变量设置一个:
<appender name="plainLogsToFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>/${LOG_PATH:-/tmp/default}/service.log</file>
</appender>
/${LOG\u路径:-/tmp/default}/service.LOG
您可以在@之前的方法中设置它:System.setProperty(key,value)
。或者,把它放在一个静态块中
<appender name="plainLogsToFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>/${LOG_PATH:-/tmp/default}/service.log</file>
</appender>