Class: UU::LoggerStderr::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/uu/logger_stderr.rb

Constant Summary collapse

DECORATION =
{
  'UNKNOWN' => { color: :red, mode: :underline },
  'FATAL' => { color: :red, mode: :underline },
  'ERROR' => :red,
  'WARN' => :yellow,
  'INFO' => :default,
  'DEBUG' => :light_black,
}.freeze
PATHS =
%w[
  /log.rb
  /logger.rb
  /loggable.rb
  /forwardable.rb
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context) ⇒ Formatter

Returns a new instance of Formatter.



19
20
21
# File 'lib/uu/logger_stderr.rb', line 19

def initialize(context)
  @context = context
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



23
24
25
# File 'lib/uu/logger_stderr.rb', line 23

def context
  @context
end

Instance Method Details

#call(severity, time, _progname, msg) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/uu/logger_stderr.rb', line 25

def call(severity, time, _progname, msg)
  loc = meaningful_location
  short_severity = severity[0, 1]
  time_format = time.utc.strftime('%T')
  context = @context.context
  context_msg = context.empty? ? '' : "#{context.to_json} "

  "#{short_severity}]#{time_format}" \
    "[#{loc[:filename]}##{loc[:method]}:#{loc[:lineno]}] " \
    "#{context_msg}" \
    "#{msg}\n".colorize(DECORATION[severity])
end

#find_locationObject



54
55
56
57
58
59
# File 'lib/uu/logger_stderr.rb', line 54

def find_location
  caller_locations.find do |location_|
    location_.path != __FILE__ &&
      PATHS.none? { |path| location_.path.end_with?(path) }
  end
end

#meaningful_locationObject



38
39
40
41
42
43
44
45
# File 'lib/uu/logger_stderr.rb', line 38

def meaningful_location
  location = find_location
  {
    filename: File.basename(location.path),
    method: location.label,
    lineno: location.lineno,
  }
end