class ApacheLog::Parser

Constants

ADDITIONAL_PATTERN
COMBINED_FIELDS
COMBINED_PATTERN
COMMON_FIELDS
COMMON_PATTERN
VERSION

Public Class Methods

new(format, additional_fields=[]) click to toggle source
# File lib/apache_log/parser.rb, line 13
def initialize(format, additional_fields=[])
  additional_pattern = ''
  additional_pattern << ADDITIONAL_PATTERN * additional_fields.size

  case format
  when 'common'
    @fields = COMMON_FIELDS + additional_fields
    @pattern = /#{COMMON_PATTERN}#{additional_pattern}/
  when 'combined'
    @fields = COMBINED_FIELDS + additional_fields
    @pattern = /#{COMBINED_PATTERN}#{additional_pattern}/
  else
    raise "format error\n no such format: <#{format}> \n"
  end
end

Public Instance Methods

parse(line) click to toggle source
# File lib/apache_log/parser.rb, line 29
def parse(line)
  matched = @pattern.match(line)

  raise "parse error\n at line: <#{line}> \n" if matched.nil?

  generate_hash(@fields, matched.to_a)
end

Private Instance Methods

generate_hash(keys, values) click to toggle source
# File lib/apache_log/parser.rb, line 39
def generate_hash(keys, values)
  keys.each.with_index(1).each_with_object({}) do |(key, i), hash|
    key = key.to_sym

    case key
    when :datetime
      hash[key] = to_datetime(values[i])
    when :request
      hash[key] = parse_request(values[i])
    else
      hash[key] = values[i]
    end
  end
end
parse_request(str) click to toggle source
# File lib/apache_log/parser.rb, line 58
def parse_request(str)
  method, path, protocol = str.split

  { method: method, path: path, protocol: protocol }
end
to_datetime(str) click to toggle source
# File lib/apache_log/parser.rb, line 54
def to_datetime(str)
  DateTime.strptime(str, '%d/%b/%Y:%T %z')
end