Skip to content

Commit

Permalink
Ensure Logback is refreshed before application starts
Browse files Browse the repository at this point in the history
  • Loading branch information
driverpt committed Oct 26, 2022
1 parent a2c0a8b commit 6da89e7
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 3 deletions.
7 changes: 7 additions & 0 deletions runtime/src/main/java/io/micronaut/logging/LoggingSystem.java
Expand Up @@ -38,4 +38,11 @@ public interface LoggingSystem {
*/
void setLogLevel(@NotBlank String name, @NotNull LogLevel level);

/**
* Refreshes Logging System with the goal of cleaning its internal caches
*
*/
default void refresh() {

}
}
Expand Up @@ -64,6 +64,7 @@ final class PropertiesLoggingLevelsConfigurer implements ApplicationEventListene
public PropertiesLoggingLevelsConfigurer(Environment environment, List<LoggingSystem> loggingSystems) {
this.environment = environment;
this.loggingSystems = loggingSystems;
initLogging();
configureLogLevels();
}

Expand All @@ -74,9 +75,12 @@ public PropertiesLoggingLevelsConfigurer(Environment environment, List<LoggingSy
*/
@Override
public void onApplicationEvent(RefreshEvent event) {
if (event.getSource().keySet().stream().anyMatch(key -> key.startsWith(LOGGER_LEVELS_PROPERTY_PREFIX))) {
configureLogLevels();
}
initLogging();
configureLogLevels();
}

private void initLogging() {
this.loggingSystems.forEach(LoggingSystem::refresh);
}

private void configureLogLevels() {
Expand Down
Expand Up @@ -40,6 +40,11 @@ public void setLogLevel(String name, LogLevel level) {
getLoggerContext().getLogger(name).setLevel(toLevel(level));
}

@Override
public void refresh() {
getLoggerContext().reset();
}

/**
* @return The logback {@link LoggerContext}
*/
Expand Down
Expand Up @@ -142,4 +142,25 @@ logger:
'foo.bar3' | Level.INFO
}

void 'logging refresh is properly called on application start'() {
given:
ApplicationContext context = ApplicationContext.builder()
.build()

def loggingSystem = context.getBean(LoggingSystem.class)
def spy = Spy(loggingSystem)

when:
SystemLambda.withEnvironmentVariable("LOGGER_LEVELS_FOO_BAR3", "INFO")
.execute(() -> {
context.start()
})

then:
1 * spy.refresh()

cleanup:
context.close()
}

}

0 comments on commit 6da89e7

Please sign in to comment.