如何在 SpringBootTest 中为 logback 设置环境变量?

How to set environment-variable in SpringBootTest for logback?

SpringBootTest如何设置环境变量进行logback配置?
在logback.xml中使用环境变量时发生Logback配置错误

在logback.xml,

<appender name="plainLogsToFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>/${LOG_PATH}/service.log</file>

这是测试-class:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class MyTestClass {
//tests here
}

报告了以下异常:

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") , 属性 显式设置值=23=]@SpringBootTest(..., 属性 ={}) 。
但是,logback 仅引用系统环境变量。
我只关心测试执行。
一些忽略 logback 的方法也很受欢迎。

使用 @Before@BeforeAllstatic 代码块来不及 为 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 {

}

您可以通过自定义 ClassRule 使用 JUnit 4 实现相同的效果。详细了解 here.

此外,您还可以为这样的变量设置一个default

<appender name="plainLogsToFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>/${LOG_PATH:-/tmp/default}/service.log</file>
</appender>