Class: Sinatra::Log::DefaultFormatter

Inherits:
Log4r::Formatter
  • Object
show all
Defined in:
lib/sinatra/log/default_formatter.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 Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(basedir = nil) ⇒ DefaultFormatter

Returns a new instance of DefaultFormatter.

Parameters:

  • basedir (String) (defaults to: nil)

    The base project directory; this directory will be filtered out from each log entry if specified.



17
18
19
20
# File 'lib/sinatra/log/default_formatter.rb', line 17

def initialize(basedir = nil)
  super
  @basedir = basedir
end

Instance Attribute Details

#basedirObject (readonly)

Returns the value of attribute basedir.



13
14
15
# File 'lib/sinatra/log/default_formatter.rb', line 13

def basedir
  @basedir
end

Instance Method Details

#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 ane line number



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/sinatra/log/default_formatter.rb', line 26

def event_filename(tracer)
  if basedir.nil?
    parts = tracer.match(/(.*:[0-9]+).*:/)
  else
    parts = tracer.match(/#{basedir}\/(.*:[0-9]+).*:/)
  end

  # 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

Receive the LogEvent and pull out the log message and format it for display in the logs

Parameters:

  • event (Log4r::LogEvent)

Returns:

  • (String)

    Formatted log message



46
47
48
49
50
# File 'lib/sinatra/log/default_formatter.rb', line 46

def format(event)
  filename = event_filename(event.tracer[1])
  time = Time.now.utc.iso8601
  return "#{Log4r::LNAMES[event.level]}: #{time}: #{filename}: #{event.data}\n"
end