User Tools

Site Tools


Watch tail of file on ruby

Two part form for web

tail.rb
#!/usr/bin/env ruby
 
file = "/var/log/debug.log"
f = File.open(file,"r")
 
# first download of page 
f.seek(-100, :END)
f.readline
f.each do |line|
    print line
end
current = f.tell
f.close
 
# jquery append
while true do
    f = File.open(file, "r")
    f.seek(current)
    f.each do | line | 
        print line
    end
    current = f.tell
    f.close
    sleep 1
end
#EOF

OOP kind

watchtail-oop.rb
#!/usr/bin/env ruby
 
class Tail 
 
    def initialize(file)
        @file = file
    end
 
    def first
        f = File.open(@file,"r")
        f.seek(-100, :END)
        f.readline
        array = Array.new
        f.each do |line|
            array.push line
        end
        @pos = f.tell
        f.close
        array
    end
 
    def last
        f = File.open(@file, "r")
        f.seek(@pos)
        array = Array.new
        f.each do |line| 
            array.push line
        end
        @pos = f.tell
        f.close
        array
    end
    def pos
        @pos
    end
    def pos=(pos)
        @pos = pos
    end
end
 
t = Tail.new("/var/log/debug.log")
puts t.first
#pos = t.pos # session store
 
while true do
#    t.pos = pos #restore fron session data
    puts t.last
 #   pos = t.pos #wrote to session data
    sleep 1
end
 
#EOF

Jquery loop by timer

timer.js
<script>
    function myTail() {
       $.get("", { next : "yet" },
         function(data){
           $("#log").append(data);
           $("#log").animate({
                bottom : "-=1000em",
            });
         });
     };
     var timerId = setInterval(
         function() { myTail(); },
         1000
     );
</script>

First PagePrevious PageBack to overview