Created
December 2, 2020 17:09
-
-
Save roamingthings/48a7096d4cf78a7e60ca3b566e98c6a4 to your computer and use it in GitHub Desktop.
How to re-initialize the Spring Boot Logging System in a Spring Boot 2.4 Test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@SpringBootTest | |
@TestPropertySource(properties = ["logging.config=classpath:logback-other.xml"]) | |
@ContextConfiguration(initializers = [LoggingSystemReinitializer::class]) | |
class LoggingMaskingDecoratorTest { | |
private val standardOut = System.out | |
private val outputStreamCaptor: ByteArrayOutputStream = ByteArrayOutputStream() | |
companion object { | |
@AfterAll | |
@JvmStatic | |
fun cleanupLoggingSystem() { | |
val system = LoggingSystem.get(LoggingSystem::class.java.classLoader) | |
system.cleanUp() | |
} | |
} | |
@BeforeEach | |
fun setUp() { | |
System.setOut(PrintStream(outputStreamCaptor)) | |
} | |
@AfterEach | |
fun tearDown() { | |
System.setOut(standardOut) | |
} | |
@Test | |
fun `should log something`() { | |
val logger = LoggerFactory.getLogger("MyLogger") | |
logger.info("Some Logging") | |
val output = outputStreamCaptor.toString().trim { it <= ' ' } | |
assertThat(output).contains("Some Logging") | |
} | |
} | |
class LoggingSystemReinitializer : ApplicationContextInitializer<ConfigurableWebApplicationContext> { | |
override fun initialize(context: ConfigurableWebApplicationContext) { | |
val environment = context.environment | |
val logConfig = environment.getProperty(CONFIG_PROPERTY) | |
if (logConfig != null) { | |
val system = LoggingSystem.get(LoggingSystem::class.java.classLoader) | |
system.cleanUp() | |
try { | |
system.initialize(LoggingInitializationContext(environment), logConfig, LogFile.get(environment)); | |
} catch (e: Exception) { | |
throw RuntimeException("Unable to reinitialize LoggingSystem: ", e) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment