Created
February 12, 2011 19:14
-
-
Save hukl/824012 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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