如何在日志文件中添加新行时检查 - Java
问题描述:
我正在使用java中的简单脚本来监视日志文件。 如何在脚本再次运行时检查文件是否已更改。 应检查发生的脚本是那句“无法” 我的脚本运行每5分钟(Windows计划)如何在日志文件中添加新行时检查 - Java
我的代码:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class LogAgent {
public static void main(String[] args)
{
double count = 0,countBuffer=0,countLine=0;
String lineNumber = "";
String filePath = "/Users/Radek/log.txt";
BufferedReader br;
String inputSearch = "Unable";
String line = "";
try {
br = new BufferedReader(new FileReader(filePath));
try {
while((line = br.readLine()) != null)
{
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(inputSearch)) {
count++;
countBuffer++;
}
}
if(countBuffer > 0)
{
countBuffer = 0;
lineNumber += countLine + ",";
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (count == 0)
{
System.out.println("Stan poprawny");
}
else
{
System.out.println("Liczba wystapien alertu--"+count);
// System.out.println("Alert w liniach--"+lineNumber);
}
}
}
答
我已经使用了类似的系统,其中“日志代理程序“会自行记录从它监视的日志文件中读取的字节数。所以每次运行代理时,都会将字节数写入另一个文件中。代理启动时,它会重新读取字节数,并在再次读取实际日志文件之前跳过许多字节。它运作良好,我建议。或者,您可以保存读取的行数而不是字节数,然后使用它。