196. Logging in predicates
We already know that the Predicate
functional interface relies on its test()
method to perform the given check, and it returns a Boolean value. Let’s suppose that we want to alter the test()
method to log the failure cases (the cases that lead to the return of a false
value).
A quick approach is to write a helper method that sneaks the logging part, as follows:
public final class Predicates {
private static final Logger logger
= LoggerFactory.getLogger(LogPredicate.class);
private Predicates() {
throw new AssertionError("Cannot be instantiated");
}
public static <T> Predicate<T> testAndLog(
Predicate<? super T> predicate, String val) {
return t -> {
boolean result = predicate.test(t);
if (!result) {
logger.warn(predicate + " don't match '" + val + "'");
}
return result;
};
}
}
Another approach consists of...