Skip to content

Instantly share code, notes, and snippets.

@hukl
Created February 12, 2011 19:14
Show Gist options
  • Save hukl/824012 to your computer and use it in GitHub Desktop.
Save hukl/824012 to your computer and use it in GitHub Desktop.
require 'time'
class LogfileParser
TIME_REGEXP = /\[\d{2}\/\w{3}\/\d{4}\:\d{2}:\d{2}:\d{2}\s.{5}\]/
def initialize path, starting_at
raise ArgumentError unless File.exists?( path )
@log = File.open( path )
@starting_at = Time.parse( starting_at )
@ending_at = (@starting_at + 300)
@bytes_to_skip = File.open( 'statefile' ) { |f| f.readline.to_i } rescue 0
end
def search
@log.rewind
if 0 == @bytes_to_skip
@log.each_line do |line|
timestamp = line.match( TIME_REGEXP )
next unless timestamp
current_time = Time.parse( timestamp[0].sub(":", " ") )
if current_time >= @starting_at
@bytes_to_skip = @log.tell
File.open( 'statefile', 'w') { |f| f.write( @bytes_to_skip ) }
break
end
end
end
end
def emit &block
search
@log.seek( @bytes_to_skip, File::SEEK_SET)
@log.each_line do |line|
timestamp = line.match( TIME_REGEXP )
next unless timestamp
current_time = Time.parse( timestamp[0].sub(":", " ") )
if current_time >= @starting_at && current_time <= @ending_at
yield line
end
return if current_time > @ending_at
end
end
end
parser = LogfileParser.new( *ARGV )
parser.emit {|l| l}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment