Search for strings in .log file in Java

1

I need to create a program where I can search a .log file and find certain strings in it, for example:

  

The network path was not found.

Among others that would represent errors in this log file, they are the ones I want to find.

Any ideas how to do this in a simple way?

    
asked by anonymous 08.05.2018 / 21:46

2 answers

1

You can get a Stream<String> matching the lines of the file using File.lines(Path) (Java 8 or higher).

Your code should look like this:

File.lines(Paths.get("seu_arquivo.log"))
        .filter(x -> x.contains("O caminho de rede não foi encontrado."))
        .forEach(System.out::println);

If you want to put the line number together:

AtomicInteger a = new AtomicInteger(0);
File.lines(Paths.get("seu_arquivo.log"))
        .map(linha -> a.incrementAndGet() + "|" + linha)
        .filter(x -> x.contains("O caminho de rede não foi encontrado."))
        .forEach(System.out::println);

This assumes that your encoding is UTF-8. If it is ISO-8859-1 or some other, use the method lines overloaded which also gets Charset :

File.lines(Paths.get("seu_arquivo.log"), StandardCharsets.ISO_8859_1)
    
08.05.2018 / 22:08
0

For the time being the code I was able to create is getting like this, the result shows 3 values with "The network path was not found" contained in this example log, but this was just to learn, as I would to add more occurrences to this program I have at least 5 or more different codes that I would like it to display as well, the main idea is to tune the occurrence of these error messages to trigger a sendmail, indicating that a problem has occurred in a given backup and deserves extra attention.

public static void main(String args[]) {

    String fileName = "C:\users\Matheus\desktop\backup_outlook.log";
    List<String> list = new ArrayList<>();

    try (Stream<String> stream = Files.lines(Paths.get(fileName),StandardCharsets.ISO_8859_1)) {

                list = stream
                        .filter(line -> line.startsWith("O caminho da rede"))
                        .collect(Collectors.toList());

    } catch (IOException e) {
        e.printStackTrace();
    }

    list.forEach(System.out::println);

}
    
09.05.2018 / 00:05