Class: RangeLogger::LogsParser

Inherits:
Object
  • Object
show all
Defined in:
lib/range_logger.rb

Constant Summary collapse

TIME_REGEXP =
/\[\d{4}\-\d{2}\-\w{3}\d{2}:\d{2}:\d{2}\.\d{6}\s#\d+\]/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ LogsParser

Returns a new instance of LogsParser.



9
10
11
12
13
# File 'lib/range_logger.rb', line 9

def initialize(options={})
  @file = File.open(options[:file])
  @from = options[:from]
  @to   = options[:to] || Time.now
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file.



5
6
7
# File 'lib/range_logger.rb', line 5

def file
  @file
end

#fromObject (readonly)

Returns the value of attribute from.



5
6
7
# File 'lib/range_logger.rb', line 5

def from
  @from
end

#toObject (readonly)

Returns the value of attribute to.



5
6
7
# File 'lib/range_logger.rb', line 5

def to
  @to
end

Instance Method Details

#format_date(date) ⇒ Object



46
47
48
# File 'lib/range_logger.rb', line 46

def format_date(date)
  date.strftime("%Y_%m_%d_%H-%M-%S")
end

#matched_logsObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/range_logger.rb', line 31

def matched_logs
  [].tap do |logs|
    file.each_line do |line|
      next unless timestamp = line.match(TIME_REGEXP)

      current_time = Time.parse(timestamp[0])
      if current_time <= to
        logs << line if current_time >= from
      else
        break
      end
    end
  end
end

#run!Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/range_logger.rb', line 15

def run!
  puts "Start date should be before end date" and return if from > to

  logs = matched_logs

  if logs.any?
    file_name = "#{format_date(from)}_#{format_date(to)}.log"
    File.write(file_name, logs.join)
    file_size = "#{(File.size(file_name)/(1024.0 * 1024.0)).round(3)} MB"

    puts "New log file #{file_name} with size #{file_size} has been successfully created"
  else
    puts "There are no mathes, try another date range"
  end
end