Class: HttpLogParser

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

Constant Summary collapse

LOG_FORMATS =
{
  :common => '%h %l %u %t \"%r\" %>s %b',
  :common_with_virtual => '%v %h %l %u %t \"%r\" %>s %b',
  :combined => '%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"',
  :combined_with_virtual => '%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"',
  :combined_with_cookies => '%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\" \"%{Cookies}i\"'
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHttpLogParser

Returns a new instance of HttpLogParser.



61
62
63
64
# File 'lib/http/parser.rb', line 61

def initialize
  @log_format = []
  initialize_known_formats
end

Instance Attribute Details

#known_formatsObject (readonly)

Returns the value of attribute known_formats.



59
60
61
# File 'lib/http/parser.rb', line 59

def known_formats
  @known_formats
end

Instance Method Details

#check_format(line) ⇒ Object



73
74
75
76
77
78
# File 'lib/http/parser.rb', line 73

def check_format(line)
  @known_formats.sort_by { |key, log_format| log_format.format_regex.source.size }.reverse.each { |key, log_format|
    return key if line.match(log_format.format_regex)
  }
  return :unknown
end

#initialize_known_formatsObject



66
67
68
69
70
71
# File 'lib/http/parser.rb', line 66

def initialize_known_formats
  @known_formats = {}
  LOG_FORMATS.each do |name, format|
    @known_formats[name] = HttpLogFormat.new(name, format)
  end
end

#parse_line(line) ⇒ Object

Raises:

  • (ArgumentError)


80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/http/parser.rb', line 80

def parse_line(line)
  @format = check_format(line)
  log_format = @known_formats[@format]
  raise ArgumentError if log_format.nil? or line !~ log_format.format_regex
  data = line.scan(log_format.format_regex).flatten
  parsed_data = {}
  log_format.format_symbols.size.times do |i|
    parsed_data[log_format.format_symbols[i]] = data[i]
  end

  parsed_data[:datetime] = parsed_data[:datetime][1...-1] if parsed_data[:datetime]
  parsed_data[:domain] = parsed_data[:ip] unless parsed_data[:domain]
  parsed_data[:format] = @format

  parsed_data
end