Watch/read a growing log file

后端 未结 7 1073
春和景丽
春和景丽 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 02:00

    There are two approach:

    • poll the file in an infinite loop (like in Qianjigui's answer, but it is good to put some sleep inside the infinite loop)
    • use OS event subsystem: kqueue on BSD, inotify on Linux

    Here is an article I wrote about this: Ruby for Admins: Reading Growing Files. So the program combining both event subsystem and polling looks like this:

    def tail_dash_f(filename)
      open(filename) do |file|
        file.read          
        case RUBY_PLATFORM   # string with OS name, like "amd64-freebsd8"
        when /bsd/, /darwin/
          require 'rb-kqueue'
          queue = KQueue::Queue.new     
          queue.watch_file(filename, :extend) do
            yield file.read             
          end
          queue.run                     
        when /linux/
          require 'rb-inotify'
          queue = INotify::Notifier.new  
          queue.watch(filename, :modify) do
            yield file.read             
          end
          queue.run                      
        else
          loop do           
            changes = file.read
            unless changes.empty?  
              yield changes
            end
            sleep 1.0       
          end
        end
      end
    end
    
    tail_dash_f ARGV.first do |data|
      print data
      if data =~ /error/i
        # do something else, for example send an email to administrator
      end
    end
    
    0 讨论(0)
提交回复
热议问题