1

I have a List<LogEntry> that I need to filter out from the list every log that is not on Level.SEVERE. And in addition I have a List of whitelisted logs that need to be filtered too. These logs are contains only partial message so I have to use contains() to identified them.

My code looks like this:

LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
List<LogEntry> logEntriesList = logEntries.getAll();

Stream<LogEntry> filtered =
    logEntriesList.stream()
                  .filter(log -> log.getLevel().equals(Level.SEVERE));
    
for (String whitelisted : whitelistedLogs) {
    filtered = filtered.filter(log -> !log.getMessage().contains(whitelisted));
}

Is there any way to avoid this for loop and get the same result?

1
  • I am reverting the edit as the answer need not be posted as part of the question. Commented Jun 29, 2021 at 9:11

2 Answers 2

1

First you filter those with SEVERE log level, then filter those which contains at least one whitelisted message:

logEntriesList.stream()
              .filter(log -> log.getLevel().equals(Level.SEVERE))
              .filter(log -> whitelistedLogs.stream().noneMatch(wl -> log.getMessage().contains(wl)))
              .collect(Collectors.toList());

Sign up to request clarification or add additional context in comments.

3 Comments

I tried your solution but it didn't worked for me at start, but it gives me a solid direction how to do it. Thanks :)
@Tal you may update the answer here. No need to update the question with the answer.
@Tal Also it is better (more readable) to use noneMatch(condition) instead of allMatch( !condition) I have updated the answer.
0

If whitelisted logs are constant, instead of list, you could create a regex from them one time. That way you could:

filtered = filtered.filter(log -> !log.getMessage().matches(whitelisted_regex));

2 Comments

I don't think that regex will be helpful in my case. The strings of the whitelisted logs are not related to each other.
If you can give example of whitelisted logs and actual logs, at least few of them, I could try to tell you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.