简体   繁体   English

模式的 java 监视器日志文件

[英]java monitor log file for a pattern

Java Monitor log File for a pattern模式的 Java 监视器日志文件

Hi everyone,嗨,大家好,

I need to make a program that will monitor a log file (in CSV format) for a specific string in each line.我需要制作一个程序来监视每行中特定字符串的日志文件(CSV 格式)。 If the string appears in the log line I want to parse the log line and extract a string from the line.如果字符串出现在日志行中,我想解析日志行并从该行中提取一个字符串。 I want to use this string for further operations (lookup local sqlite DB, update other system using API) but I've done all those before I can handle that part.我想使用这个字符串进行进一步的操作(查找本地 sqlite 数据库,使用 API 更新其他系统),但我在处理那部分之前已经完成了所有这些操作。

I need the monitoring to be continous in a "listening" state kind of like tail -f |我需要在类似于 tail -f | 的“侦听”状态下进行连续监视grep -i "pattern". grep -i “模式”。

I have been looking options and found this so far.到目前为止,我一直在寻找选项并找到了这一点。 https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/input/Tailer.html https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/input/Tailer.html

but I'm not sure as to how I can filter the output using java.util.regex.*但我不确定如何使用 java.util.regex.* 过滤输出

I'm looking for the easiest alternative to get this done.我正在寻找最简单的替代方法来完成这项工作。 Can anyone provide better alternatives or some guidance as to how to use apache commons Tailer?任何人都可以提供更好的替代方案或有关如何使用 apache commons Tailer 的一些指导吗?

The following example uses Java's WatchService to register a directory listener.以下示例使用 Java 的 WatchService 注册目录侦听器。 Whenever the watched file changes, the file is read, skipping any previously read content.每当监视的文件发生更改时,都会读取该文件,跳过任何先前读取的内容。 It uses a regular expression to match on new lines coming in, looking for a key word.它使用正则表达式来匹配进入的新行,寻找关键字。 In this case "WARN|ERROR".在这种情况下,“警告|错误”。

package com.example;包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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM