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

#initialize(formats = nil) ⇒ HttpLogParser

Returns a new instance of HttpLogParser.



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/http/parser.rb', line 61

def initialize(formats = nil)

  case formats
    when String then
      @formats = { :provided => formats }
    when Hash then
      @formats = formats
    else
      @formats = {}
      LOG_FORMATS.each do |name, format|
        @formats[name] = HttpLogFormat.new(name, format)
      end
  end

end

Instance Attribute Details

#formatsObject (readonly)

Returns the value of attribute formats.



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

def formats
  @formats
end

Instance Method Details

#format_from_line(line) ⇒ Object



77
78
79
80
81
82
# File 'lib/http/parser.rb', line 77

def format_from_line(line)
  @formats.sort_by { |key, format| format.format_regex.source.size }.reverse.each { |key, format|
    return @formats[key] if line.match(format.format_regex)
  }
  return nil
end

#parse_line(line) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/http/parser.rb', line 84

def parse_line(line)

  if @format.nil?
    @format = format_from_line(line)
    raise "Failed to detect format" if @format.nil?
  end

  raise "Line does not match format" if line !~ @format.format_regex

  data = line.scan(@format.format_regex).flatten
  parsed_data = {}
  @format.format_symbols.size.times do |i|
    parsed_data[@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