Apache Commons IO Tailer example

前端 未结 2 1052
情话喂你
情话喂你 2020-12-15 21:56

I am working on a monitoring program that reads the /var/log/auth.log file. I am using Apache Commons IO Tailer class to read the file in real time. To get started, I wanted

相关标签:
2条回答
  • 2020-12-15 22:06

    Based on my testing, Tailer will only print a line when you've added a newline to the file. So try sudo echo "Hello\n" >> log.txt

    Also note that if you call create, you start a thread but have no handle on it. Hence why you had to have a while/true loop.

    You could try this instead:

    public static void main(String[] args) {
        TailerListener listener = new MyListener();
        Tailer tailer = new Tailer(new File("log.txt"), listener, 500);        
        tailer.run();
    }
    
    0 讨论(0)
  • 2020-12-15 22:19

    Your code should work. For me, this does works as expected.

    package de.lhorn.stackoverflowplayground;
    
    import java.io.File;
    import org.apache.commons.io.input.Tailer;
    import org.apache.commons.io.input.TailerListenerAdapter;
    
    public class App {
    
        private static final int SLEEP = 500;
    
        public static void main(String[] args) throws Exception {
            App app = new App();
            app.run();
        }
    
        private void run() throws InterruptedException {
            MyListener listener = new MyListener();
            Tailer tailer = Tailer.create(new File("/tmp/log.txt"), listener, SLEEP);
            while (true) {
                Thread.sleep(SLEEP);
            }
        }
    
        public class MyListener extends TailerListenerAdapter {
    
            @Override
            public void handle(String line) {
                System.out.println(line);
            }
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题