Skip to content

Instantly share code, notes, and snippets.

@roamingthings
Created December 2, 2020 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roamingthings/48a7096d4cf78a7e60ca3b566e98c6a4 to your computer and use it in GitHub Desktop.
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
@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