Jboss log reading

Asked

Viewed 423 times

1

This code takes my file from log Jboss and displays the first 1000 lines. I wonder how I display the last 1000 lines?

private String log;

public void pesquisar() {

    String diretorioCorrente = System.getProperty("jboss.server.log.dir");

    File file = new File(diretorioCorrente + File.separator + "server.log");
    try {
        FileReader reader = new FileReader(file);
        BufferedReader input = new BufferedReader(reader);
        String linha;
        int contador = 0;
        StringBuilder sb = new StringBuilder();
        while ((linha = input.readLine()) != null) {
            sb.append(linha + "\n");
            contador++;
            if (contador > 1001) {
                break;
            }
        }
        input.close();
        log = sb.toString();
    } catch (IOException ioe) {
        System.out.println(ioe);
    }
}
  • Remove this if: if(counter > 1001){break;}. And check if it will read the other lines.

1 answer

2

The bad news

You will have to read the entire file to recover the last lines.

The good news

With the Java Collections API classes it is easy to recover the latest N lines.

Procedure

First, declare a ArrayList before the while and add each line to the list instead of the StringBuffer.

Then remove the stop criterion if (contador > 1001), as already suggested the @adelmo00.

This way, your method will return all the lines, right?

Finally, remove the "older" lines from the array when their number exceeds 1000. Example:

public void pesquisar() {

    String diretorioCorrente = System.getProperty("jboss.server.log.dir");

    File file = new File(diretorioCorrente + File.separator + "server.log");
    try {
        FileReader reader = new FileReader(file);
        BufferedReader input = new BufferedReader(reader);
        String linha;
        int contador = 0;
        //inicia com um array interno de 1000 posições
        List<String> list = new ArrayList<String>(1000); 
        //adiciona todos os elementos, mas quando chegar a 1000, remove os mais velhos
        while ((linha = input.readLine()) != null) {
            list.add(linha);
            contador++;
            if (contador > 1000) {
                linha.remove(0);
            }
        }
        //escreve no StringBuffer, mas talvez não seja necessário
        StringBuilder sb = new StringBuilder();
        for (String str : list) {
            sb.append(str + "\n");
        }
        input.close();
        log = sb.toString();
    } catch (IOException ioe) {
        System.out.println(ioe);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.