Class: Lumberjack::Formatter::TruncateFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/lumberjack/formatter/truncate_formatter.rb

Overview

Truncate a string object to a specific length. This is useful for formatting messages when there is a limit on the number of characters that can be logged per message. This formatter should only be used when necessary since it is a lossy formatter.

When a string is truncated, it will have a unicode ellipsis character (U+2026) appended to the end of the string.

Instance Method Summary collapse

Constructor Details

#initialize(length = 32768) ⇒ TruncateFormatter

Returns a new instance of TruncateFormatter.

Parameters:

  • length (Integer) (defaults to: 32768)

    The maximum length of the string (defaults to 32K).



16
17
18
# File 'lib/lumberjack/formatter/truncate_formatter.rb', line 16

def initialize(length = 32768)
  @length = length
end

Instance Method Details

#call(obj) ⇒ String, Object

Truncate a string if it exceeds the maximum length.

Parameters:

  • obj (Object)

    The object to format. If it's a string longer than the maximum length, it will be truncated. Other objects are returned unchanged.

Returns:

  • (String, Object)

    The truncated string or original object.



25
26
27
28
29
30
31
# File 'lib/lumberjack/formatter/truncate_formatter.rb', line 25

def call(obj)
  if obj.is_a?(String) && obj.length > @length
    "#{obj[0, @length - 1]}"
  else
    obj
  end
end