Dav*_*ron -2 java logging text file monitor
嗨,大家好,
我需要制作一个程序来监视每行中特定字符串的日志文件(CSV 格式)。如果字符串出现在日志行中,我想解析日志行并从该行中提取一个字符串。我想使用这个字符串进行进一步的操作(查找本地 sqlite 数据库,使用 API 更新其他系统),但我在处理那部分之前已经完成了所有这些。
我需要在类似于 tail -f | 的“侦听”状态下进行连续监视 grep -i “模式”。
到目前为止,我一直在寻找选项并找到了这一点。 https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/input/Tailer.html
但我不确定如何使用 java.util.regex.* 过滤输出
我正在寻找最简单的替代方法来完成这项工作。任何人都可以提供更好的替代方案或有关如何使用 apache commons Tailer 的一些指导吗?
小智 6
以下示例使用 Java 的 WatchService 注册目录侦听器。每当监视的文件发生更改时,都会读取该文件,跳过任何先前读取的内容。它使用正则表达式来匹配进入的新行,寻找关键字。在这种情况下,“警告|错误”。
包com.example;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
public class LogScanner
{
Path logFile = Paths.get("app.log");
private int lines = 0;
private int characters = 0;
public static void main(String[] args)
{
new LogScanner().run();
}
public void run()
{
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
try (BufferedReader in = new BufferedReader(new FileReader(logFile.toFile()))) {
String line;
while ((line = in.readLine()) != null) {
lines++;
characters += line.length() + System.lineSeparator().length();
}
}
logFile.toAbsolutePath().getParent().register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
do {
WatchKey key = watcher.take();
System.out.println("Waiting...");
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent<Path> pathEvent = (WatchEvent<Path>) event;
Path path = pathEvent.context();
if (path.equals(logFile)) {
try (BufferedReader in = new BufferedReader(new FileReader(pathEvent.context().toFile()))) {
String line;
Pattern p = Pattern.compile("WARN|ERROR");
in.skip(characters);
while ((line = in.readLine()) != null) {
lines++;
characters += line.length() + System.lineSeparator().length();
if (p.matcher(line).find()) {
// Do something
System.out.println(line);
}
}
}
}
}
key.reset();
} while (true);
} catch (IOException | InterruptedException ex) {
Logger.getLogger(LogScanner.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
}
}
}
Run Code Online (Sandbox Code Playgroud)