Skip to content

Commit

Permalink
Refactored duplicate code
Browse files Browse the repository at this point in the history
  • Loading branch information
Hakky54 committed Feb 5, 2023
1 parent 69b588d commit b760bc4
Showing 1 changed file with 13 additions and 16 deletions.
29 changes: 13 additions & 16 deletions src/main/java/nl/altindag/log/LogCaptor.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import nl.altindag.log.appender.InMemoryAppender;
import nl.altindag.log.model.LogEvent;
import nl.altindag.log.util.JavaUtilLoggingLoggerUtils;
import nl.altindag.log.util.Mappers;
import nl.altindag.log.util.ValidationUtils;
import org.slf4j.LoggerFactory;

Expand All @@ -33,10 +34,10 @@
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toList;
import static nl.altindag.log.util.Mappers.toLogEvent;
import static org.slf4j.Logger.ROOT_LOGGER_NAME;

/**
Expand Down Expand Up @@ -93,11 +94,7 @@ public static LogCaptor forName(String name) {
}

public List<String> getLogs() {
synchronized (eventsCollector) {
return eventsCollector.stream()
.map(ILoggingEvent::getFormattedMessage)
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
}
return getLogs(logEvent -> true, ILoggingEvent::getFormattedMessage);
}

public List<String> getInfoLogs() {
Expand All @@ -121,19 +118,19 @@ public List<String> getTraceLogs() {
}

private List<String> getLogs(Level level) {
synchronized (eventsCollector) {
return eventsCollector.stream()
.filter(logEvent -> logEvent.getLevel() == level)
.map(ILoggingEvent::getFormattedMessage)
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
}
return getLogs(logEvent -> logEvent.getLevel() == level, ILoggingEvent::getFormattedMessage);
}

public List<LogEvent> getLogEvents() {
return getLogs(logEvent -> true, Mappers.toLogEvent());
}

private <T> List<T> getLogs(Predicate<ILoggingEvent> logEventPredicate, Function<ILoggingEvent, T> logEventMapper) {
synchronized (eventsCollector) {
return eventsCollector.stream()
.map(toLogEvent())
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
.filter(logEventPredicate)
.map(logEventMapper)
.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
}
}

Expand Down

0 comments on commit b760bc4

Please sign in to comment.