Class: Shog::Formatter

Inherits:
ActiveSupport::Logger::SimpleFormatter
  • Object
show all
Includes:
ActiveSupport::TaggedLogging::Formatter
Defined in:
lib/shog/formatter.rb

Overview

A rails logger formatter that spices up the log message adding color to and context to log messages.

Shog automatically overrides the default formatter in your rails app. Use configure to configure the default logger.

Configuration collapse

Instance Method Summary collapse

Constructor Details

#initializeFormatter

Returns a new instance of Formatter.



15
16
17
# File 'lib/shog/formatter.rb', line 15

def initialize
  reset_config!
end

Instance Method Details

#call(severity, time, progname, msg) ⇒ String

Called by the logger to prepare a message for output.

Returns:

  • (String)


21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/shog/formatter.rb', line 21

def call( severity, time, progname, msg )
  return if msg.blank? || _silence?( msg )

  msg = [
    _tagged( time, :timestamp ),
    _tagged( progname, :progname ),
    formatted_severity_tag( severity ),
    formatted_message( severity, msg )
  ].compact.join(" ")

  super severity, time, progname, msg
end

#configure { ... } ⇒ Formatter

Set up log message formatting for this formatter.

Examples:

Formatter.new.configure do
  with :defaults
  timestamp
  severity(:error){ |msg| msg.red }
  severity(:fatal){ |msg| "\b#{msg}".red }
end

Yields:

  • and executes the block where self is this formatter.

Returns:



106
107
108
109
# File 'lib/shog/formatter.rb', line 106

def configure( &block )
  instance_eval( &block )
  self
end

#format_time(time, expected = 30) ⇒ String

Formats a time value expressed in ms, adding color to highlight times outside the expected range.

If time is more than expected it's highlighted yellow. If it's more than double it's highlighted red.

Parameters:

  • time (String)

    in ms.

  • expected (Float) (defaults to: 30)

    maximum amount of time it should have taken.

Returns:

  • (String)

    the formatted time.



81
82
83
84
85
86
87
88
# File 'lib/shog/formatter.rb', line 81

def format_time( time, expected = 30 )
  timef = time.uncolorize.to_f
  case
  when timef > expected * 2 then time.to_s.uncolorize.red
  when timef > expected     then time.to_s.uncolorize.yellow
  else time
  end
end

#formatted_message(severity, msg) ⇒ String

Formats the message according to the configured #match blocks.

Parameters:

  • msg (String)

    to format.

Returns:

  • (String)

    the formatted message.



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/shog/formatter.rb', line 38

def formatted_message( severity, msg )
  msg = String === msg ? msg : msg.inspect

  if args = _matched( msg )
    args.first.call msg, args.last
  elsif proc = configuration[:severities][severity]
    proc.call msg
  else
    msg
  end
end

#formatted_severity_tag(severity) ⇒ String

Formats the severity indicator prefixed before each line when writing to the log.

Parameters:

  • the (String)

    severity of the message (ex DEBUG, WARN, etc.)

Returns:

  • (String)

    formatted version of the severity



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/shog/formatter.rb', line 55

def formatted_severity_tag( severity )
  length = configuration[:severity_tags][:_length] ||= begin
    configuration[:severity_tags].reduce(0){ |l,(k,_)| [k.length,l].max }
  end

  return if length == 0

  padded_severity = severity.ljust length

  formatted = if proc = configuration[:severity_tags][severity]
                proc.call padded_severity
              else
                padded_severity
              end
  _tagged formatted, :severity_tags
end

#match(pattern, proc) ⇒ Formatter #match(pattern) {|message, last_match| ... } ⇒ Formatter

Re-format any log messages that match the given pattern.

Examples:

configure do
  match /GET (?<address>.*)/ do |message,last_match|
    "GETTING -> #{last_match['address'].green}"
  end
end

Overloads:

  • #match(pattern, proc) ⇒ Formatter

    Parameters:

    • pattern (Regexp)

      to match against the log message.

    • proc (#call(message,last_match))

      a callable object that receives the message and the last match and re-formats the message.

  • #match(pattern) {|message, last_match| ... } ⇒ Formatter

    Parameters:

    • pattern (Regexp)

      to match against the log message.

    Yield Parameters:

    • message (String)

      the matched log message.

    • last_match (MatchData)

      the regex matches.

    Yield Returns:

    • (String)

      the re-formatted message.

Returns:



193
194
195
196
197
# File 'lib/shog/formatter.rb', line 193

def match( pattern, proc = nil, &block )
  proc ||= block
  configuration[:matchers][pattern] = proc
  self
end

#progname(enable = true) ⇒ Formatter

Include the progname in logged messages.

Parameters:

  • enable (Boolean) (defaults to: true)

    or disable tagging with the prog name of log messages.

Returns:



266
267
268
269
# File 'lib/shog/formatter.rb', line 266

def progname( enable = true )
  configuration[:progname] = enable
  self
end

#reset_config!Formatter

Resets any previously configured formatting settings.

Returns:



163
164
165
166
167
168
169
170
171
# File 'lib/shog/formatter.rb', line 163

def reset_config!
  @configuration = {
    severity_tags: {},
    severities: {},
    matchers: {},
    silencers: []
  }
  self
end

#severity(level, proc) ⇒ Formatter #severity(level) {|msg| ... } ⇒ Formatter

Provide default formatting for messages of the given severity when a #match is not found.

Examples:

configure do
  severity(:fatal){ |msg| msg.white_on_red }
end

Overloads:

  • #severity(level, proc) ⇒ Formatter

    Parameters:

    • level (String, Symbol)

      to format.

    • proc (#call(msg))

      that receives the message and returns the reformatted message.

  • #severity(level) {|msg| ... } ⇒ Formatter

    Parameters:

    • level (String, Symbol)

      to format.

    Yield Parameters:

    • msg (String)

      the message to reformat.

    Yield Returns:

    • (String)

      the reformatted message.

Returns:



155
156
157
158
159
# File 'lib/shog/formatter.rb', line 155

def severity( level, proc = nil, &block )
  proc ||= block
  configuration[:severities][ level.to_s.upcase ] = proc
  self
end

#severity_tag(level, proc) ⇒ Formatter #severity_tag(level) {|level| ... } ⇒ Formatter

Format the severity indicator tagged before each line. To format the actual message itself use #severity.

Examples:

configure do
  severity_tag(:warn){|level| level.yellow }
  severity_tag(:error){|level| level.red }
end

Overloads:

  • #severity_tag(level, proc) ⇒ Formatter

    Parameters:

    • level (String, Symbol)

      to format.

    • proc (#call(level))

      that receives the log level and returns the reformatted level.

  • #severity_tag(level) {|level| ... } ⇒ Formatter

    Parameters:

    • level (String, Symbol)

      to format.

    Yield Parameters:

    • level (String)

      the log level to reformat.

    Yield Returns:

    • (String)

      the reformatted level.

Returns:



131
132
133
134
135
# File 'lib/shog/formatter.rb', line 131

def severity_tag( level, proc = nil, &block )
  proc ||= block
  configuration[:severity_tags][ level.to_s.upcase ] = proc
  self
end

#silence(pattern) ⇒ Formatter

When a log message matches the given pattern don't log it.

Examples:

configure do
  silence /assets\/bootstrap/
end

Parameters:

  • pattern (Regexp)

    to match.

Returns:



209
210
211
212
# File 'lib/shog/formatter.rb', line 209

def silence( pattern )
  configuration[:silencers] << pattern
  self
end

#timestamp(enable = true) ⇒ Formatter

Include timestamp in logged messages.

Parameters:

  • enable (Boolean) (defaults to: true)

    or disable timestamping of log messages.

Returns:



258
259
260
261
# File 'lib/shog/formatter.rb', line 258

def timestamp( enable = true )
  configuration[:timestamp] = enable
  self
end

#with(mod) ⇒ Formatter

Use configuration defined in the given module.

When mod is a symobl, it loads one of the modules from Shog::Formatters and uses any configuration options sepcified in that module.

Otherwise mod must respond to #configure taking a single argument - this formatter.

Examples:

Built-in Formatters

configure do
  with :defaults
  with :requests
end

Custom Shared Formatters

module MyFormatters
  def self.configure( formatter )
    formatter.configure do
      timestamp
    end
  end
end

configure do
  with MyFormatters
end

Parameters:

  • mod (Symobl, #configure)

    the name of the shog module to use or an object that responds to #configure.

Returns:



246
247
248
249
250
251
252
253
# File 'lib/shog/formatter.rb', line 246

def with( mod )
  unless mod.is_a? Module
    mod = "Shog::Formatters::#{mod.to_s.camelize}".constantize
  end

  mod.configure self
  self
end