Class: Herokulogs::Formatter

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

Constant Summary collapse

FORMAT =
Regexp.new([
  /(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+\+\d{2}:\d{2}) /,
  /([^:]+): /,
  /at=(\S+) /,
  /method=(\S+) /,
  /path=(\S+) /,
  /host=(\S+) /,
  /fwd="([^"]+)" /,
  /dyno=(\S+) /,
  /connect=(\d+)ms /,
  /service=(\d+)ms /,
  /status=(\d+) /,
  /bytes=(\d+)/
].join)
OUTPUT_FORMAT_OPTIONS =
{
  "2" => :status,
  "b" => :bytes,
  "c" => :connect,
  "d" => :date,
  "f" => :fwd,
  "h" => :host,
  "l" => :log_level,
  "m" => :method,
  "p" => :path,
  "s" => :service,
  "t" => :type,
  "y" => :dyno,
}
FORMATTER =
{
  :status => "%3d",
  :bytes  => "%08d",
  :connect => "%05dms",
  :date => lambda {|e| t = Time.parse(e); t.strftime "%Y-%m-%d %H:%M:%S"},
  :fwd => "%15s",
  :host => "%20s",
  :log_level => "%5s",
  :method => "%7s",
  :path => "%-40s",
  :service => "%05dms",
  :type => "%15s",
  :dyno => "%8s"
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(format_string) ⇒ Formatter

Returns a new instance of Formatter.



50
51
52
53
54
55
56
57
# File 'lib/herokulogs/formatter.rb', line 50

def initialize(format_string)
  output_format = format_string
  if output_format.empty?
    STDERR.puts "herokulogs format missing"
    exit(false)
  end
  @output_format = output_format.chars.map {|c| OUTPUT_FORMAT_OPTIONS[c]}.compact
end

Instance Attribute Details

#output_formatObject (readonly)

Returns the value of attribute output_format.



48
49
50
# File 'lib/herokulogs/formatter.rb', line 48

def output_format
  @output_format
end

Instance Method Details

#format(line) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/herokulogs/formatter.rb', line 59

def format(line)
  input = construct_input_hash(line)
  return unless input

  @output_format.map do |element|
    formatter = FORMATTER[element]
    if formatter.respond_to?(:call)
      formatter.call(input[element])
    else
      formatter % input[element]
    end
  end.join(" ")
end