Class: Lookout::Rack::Utils::LookoutFormatter

Inherits:
Log4r::Formatter
  • Object
show all
Defined in:
lib/lookout/rack/utils/log.rb

Overview

Formatter that include the filename and relative path, and line number in output of the caller.

Since all callers go through the methods defined in this class to log, we look at the second line of the tracer output, removing everything but the directories after the project directory.

Instance Method Summary collapse

Instance Method Details

#basedirString

Return the project base directory for filtering to help with identifiying the filename and line number when formatting the log message

Returns:

  • (String)

    Base directory for the project



66
67
68
# File 'lib/lookout/rack/utils/log.rb', line 66

def basedir
  @basedir ||= File.expand_path(File.join(File.dirname(__FILE__), ".."))
end

#common_basedir(tracer) ⇒ String

Return the common base directory between this project and the given trace. If no common base directory is found, return basedir.

This memoizes the result, which can be bad if the first log comes from an unusual place. However, in all current uses this is running from an unpacked jar/war and its vastly faster to memoize the result.

Parameters:

  • tracer (String)

    A line from the LogEvent#tracer Array

Returns:

  • (String)

    Common base directory with the trace



81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/lookout/rack/utils/log.rb', line 81

def common_basedir(tracer)
  return @common_basedir if @common_basedir

  basedir_pieces = basedir.split(File::SEPARATOR)
  trace_pieces = tracer.split(File::SEPARATOR)
  i = 0
  while basedir_pieces[i] == trace_pieces[i]
    i += 1
  end
  # If there were no common directories (besides /), return our basedir
  @common_basedir = (i <= 1) ? basedir : basedir_pieces[0...i].join(File::SEPARATOR)
end

#event_filename(tracer) ⇒ String

Return a trimmed version of the filename from where a LogEvent occurred

Parameters:

  • tracer (String)

    A line from the LogEvent#tracer Array

Returns:

  • (String)

    Trimmed and parsed version of the file and line number



97
98
99
100
101
102
103
104
105
106
107
# File 'lib/lookout/rack/utils/log.rb', line 97

def event_filename(tracer)
  base = common_basedir(tracer)
  parts = tracer.match(/#{base}\/(.*:[0-9]+).*:/)

  # If we get no matches back, we're probably in a jar file in which case
  # the format of the tracer is going to be abbreviated
  if parts.nil?
    parts = tracer.match(/(.*:[0-9]+).*:/)
  end
  return parts[-1] if parts
end

#format(event) ⇒ String

Returns Formatted log message.

Returns:

  • (String)

    Formatted log message



114
115
116
117
118
119
# File 'lib/lookout/rack/utils/log.rb', line 114

def format(event)
  filename = event_filename(event.tracer[1])
  # CCYY-MM-DDThh:mm:ss.sssTZD
  time = Time.now.utc.iso8601 3
  return "#{Log4r::LNAMES[event.level]}: #{time}: #{filename}: #{event.data}\n"
end