Watch/read a growing log file

后端 未结 7 1101
春和景丽
春和景丽 2020-12-08 00:54

I have a log file that is constantly growing. How can I watch and parse it via a Ruby script?

The script will parse each new line as it is written to the file and ou

7条回答
  •  北海茫月
    2020-12-08 01:52

    You can use Kernel#select in the following way:

    def watch_for(file,pattern)
       f = File.open(file,"r")
    
       # Since this file exists and is growing, seek to the end of the most recent entry
       f.seek(0,IO::SEEK_END)
    
       while true
          select([f])
          puts "Found it!" if f.gets =~ pattern
       end
    end
    

    Then call it like:

    watch_for("some_file", /ERROR/)
    

    I've elided all error checking and such - you will want to have that and probably some mechanism to break out of the loop. But the basic idea is there.

提交回复
热议问题