class NginxLogParser

Constants

DEFAULT_FORMAT
PIECES
VERSION

Attributes

file[RW]
format[RW]
live[RW]

Public Class Methods

new(file = nil, live: false, format: nil) click to toggle source
# File lib/nginx_log_parser.rb, line 10
def initialize(file = nil, live: false, format: nil)
  self.file = file
  self.live = live
  self.format = format || DEFAULT_FORMAT

  if file =~ /\.gz$/ and live
    raise StandardError.new "Cannot live stream a .gz file"
  end
end

Public Instance Methods

each_entry() { |parse_line(gets)| ... } click to toggle source
# File lib/nginx_log_parser.rb, line 20
def each_entry
  begin
    f = File.open(file)

    if live
      f.seek(0, IO::SEEK_END)
      while true do
        sleep 0.1 while f.eof?
        yield parse_line(f.gets)
      end
    else
      f.each_line do |line|
        yield parse_line(line)
      end
    end

  ensure
    f.close if f
  end
end
format=(new_format) click to toggle source
# File lib/nginx_log_parser.rb, line 52
def format=(new_format)
  @format = new_format

  # Force regex generation
  @fmt = nil
end
parse_line(line) click to toggle source
# File lib/nginx_log_parser.rb, line 41
def parse_line(line)
  re = format_regex

  pieces = line.match(/#{re}/i)
  matches = Hash[pieces.names.map(&:to_sym).zip(pieces.captures)]
  matches[:status] = matches[:status].to_i if matches[:status]
  matches[:body_bytes_sent] = matches[:body_bytes_sent].to_i if matches[:body_bytes_sent]

  matches
end

Private Instance Methods

format_regex() click to toggle source
# File lib/nginx_log_parser.rb, line 78
def format_regex
  @fmt ||= begin
    fmt = format.dup

    # Escape reserved regex symbols
    # Notice that we do not escape the $ symbol
    escapes = %w( ( ) + ? * . \\ . | ^ ) + [ '[', ']' ]
    escapes.each do |char|
      fmt.gsub!(char, "\\\\#{char}")
    end

    puts fmt

    # Replace $vars with regexes
    PIECES.each do |find, replace|
      fmt.gsub!("$#{find}", "(?<#{find}>#{replace})")
    end

    fmt.gsub!(/ /, "\\s+")
    fmt
  end
end