Class: Munchies::Logfile
Constant Summary collapse
- TIME_REGEXP =
Matches timestamps in logfile
/^\d{4}-\d{2}-\d{2}T\d{2}\:\d{2}\:\d{2}\b/
Instance Method Summary collapse
- #backwards ⇒ Object
- #each(&block) ⇒ Object
-
#initialize(path, starting_at = Time.now) ⇒ Logfile
constructor
A new instance of Logfile.
Constructor Details
#initialize(path, starting_at = Time.now) ⇒ Logfile
Returns a new instance of Logfile.
11 12 13 14 15 16 17 |
# File 'lib/munchies.rb', line 11 def initialize path, starting_at = Time.now raise ArgumentError unless File.exists?( path ) @log = File.open( path ) @ending_at = starting_at @starting_at = (@ending_at - 300) end |
Instance Method Details
#backwards ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/munchies.rb', line 19 def backwards filesize = @log.stat.size buffer_size = 128000 offset = buffer_size # Seek to the end of the file @log.seek(0, File::SEEK_END) = @starting_at.strftime("%FT%T") while @log.tell > 0 @log.seek(-offset, File::SEEK_END) buffer = @log.read( buffer_size ) # Look at the first two lines of the buffer and check if we are close # to the desired timestamp. First line may be incomplete. # buffer_line = buffer.split("\n")[1] if (t = buffer_line.match(TIME_REGEXP)) && (t[0] < ) (1..300).each do |i| if index = buffer.index( ) # Calculate byte offest and seek to this position position = (@log.tell - buffer_size + index) @log.seek( position, File::SEEK_SET ) return end # If the first timestamp doesn't match count up seconds until it does = (@starting_at + i).strftime("%FT%T") end end offset += buffer_size return if offset > filesize end end |
#each(&block) ⇒ Object
62 63 64 65 66 67 68 |
# File 'lib/munchies.rb', line 62 def each &block backwards @log.each_line do |line| yield line end end |