Então, estou tentando fazer um logger que possa ser visualizado em uma pagina HTML, em tempo real. A pagina carrega todos os arquivos .log's (de: /clearing-dit/logs/) e possibilita clicar em cada um para mostrar seu conteúdo.
<button type="submit" class="list-group-item link">
<i class="fa fa-fw fa-history"></i> [[${l.filename}]]
<span class="badge" th:text="${#dates.format(l.lastModified,'dd/MM/YYYY HH:mm:ss')}">10/09/1992 23:55:23</span>
<span class="badge" th:text="${#numbers.formatDecimal(l.size, 1, 3)}+MB">10MB</span>
</button>
Uma vez selecionado o arquivo, é pego as ultimas 50 linhas do .log ( que é como se fosse um .txt)
public void fileNumberLines(Log log) throws IOException {
InputStream inputStream = new BufferedInputStream(new FileInputStream(logsDir + "/" + log.getFilename()));
try {
byte[] byteArray = new byte[1024];
int count = 0;
int readChar = 0;
while ((readChar = inputStream.read(byteArray)) != -1) {
for (int i = 0; i < readChar; ++i) {
if (byteArray[i] == '\n') {
++count;
}
}
}
log.setFinalLine(count);
log.setInitLine(count - 50 > 0 ? count - 50 : 0);
} finally {
inputStream.close();
}
}
E retornado o conteúdo dessas 50:
private String getLogContentByRange(int lineOccurrence, int firstLine, int lastLine, String logPath) {
BufferedReader buffRead;
int lineNumber = 1;
String content = "";
File file = new File(logPath);
try {
buffRead = new BufferedReader(new FileReader(file));
String line = null;
do {
line = "";
line = buffRead.readLine();
if (lineNumber <= lastLine && lineNumber >= firstLine) {
if (lineNumber == lineOccurrence) {
content += "<mark style='background-color: red; color: white;'>" + lineNumber + ". " + line + "</mark>\n";
} else {
content += lineNumber + ". " + line + "\n";
}
}
lineNumber++;
} while (line != null);
} catch (IOException e) {
logger.error(e.getMessage());
}
return content;
}
}
Esse log é retornado e acessado no HTML:
<div class="panel-body">
<pre>
<p th:utext="${log.content}">Log content</p>
</pre>
</div>
O meu problema é: Como eu faço para continuar "printando" as informações de um arquivo, conforme ele vai sendo incrementado/editado? Existe algum jeito de deixar a verificação "ociosa", a espera de novas atualizações? Queria fazer como se os dados estivessem sendo vistos em um console, onde é possível dar o comando grep e derivados.
WatchService
que permite "monitorar" uma pasta por alterações, o que dispara um evento e você pode ler novamente o log quando ele for alterado. Aqui um exemplo do SO em inglês: stackoverflow.com/a/16251508/4730201