class TeeLogger::Formatter
The formatter class accepts a format string, but in a different format from Kernel#sprintf. Instead, placeholders enclosed in {} (but without the Ruby- typical #, so not #{}) will get replaced with the output of the functions defined in FormatterPlaceholders
.
The class also defines a few example format strings as constants.
Constants
- FORMAT_DEFAULT
Default format string
- FORMAT_DJB
DJB format using Tai64N labels
- FORMAT_LOGGER
Format string most similar to the Ruby logger
- FORMAT_SHORT
Shorter format string
- PLACEHOLDERS
Valid placeholder to use in the format string
Public Class Methods
new(format = FORMAT_DEFAULT)
click to toggle source
Implementation
# File lib/teelogger/formatter.rb, line 82 def initialize(format = FORMAT_DEFAULT) @format = format end
Public Instance Methods
call(*args)
click to toggle source
# File lib/teelogger/formatter.rb, line 86 def call(*args) # shortern *args; the same pattern as placeholders is used # Formatting the message means replacing each placeholder with results # from the placeholder function. We're caching results to save some time. cache = {} message = @format.dup PLACEHOLDERS.each do |placeholder| value = nil begin value = cache.fetch(placeholder, ::TeeLogger::FormatterPlaceholders.send(placeholder.to_sym, *args)) cache[placeholder] = value rescue NoMethodError raise "Invalid formatter placeholder used in format string: #{placeholder}" end message.gsub!(/{#{placeholder}}/, value) end return message end