Class: Lumberjack::Formatter::DateTimeFormatter

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

Overview

Format a Date, Time, or DateTime object. If you don’t specify a format in the constructor, it will use the ISO-8601 format with microsecond precision. This formatter provides consistent date/time representation across your application logs.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(format = nil) ⇒ DateTimeFormatter

Returns a new instance of DateTimeFormatter.

Parameters:

  • format (String, nil) (defaults to: nil)

    The format to use when formatting the date/time object. If nil, uses ISO-8601 format with microsecond precision.



17
18
19
# File 'lib/lumberjack/formatter/date_time_formatter.rb', line 17

def initialize(format = nil)
  @format = format.dup.to_s.freeze unless format.nil?
end

Instance Attribute Details

#formatObject (readonly)

Returns the value of attribute format.



13
14
15
# File 'lib/lumberjack/formatter/date_time_formatter.rb', line 13

def format
  @format
end

Instance Method Details

#call(obj) ⇒ String

Format a date/time object using the configured format.

Parameters:

  • obj (Date, Time, DateTime, Object)

    The object to format. Should respond to strftime (for custom format) or iso8601 (for default format).

Returns:

  • (String)

    The formatted date/time string.



26
27
28
29
30
31
32
33
34
# File 'lib/lumberjack/formatter/date_time_formatter.rb', line 26

def call(obj)
  if @format && obj.respond_to?(:strftime)
    obj.strftime(@format)
  elsif obj.respond_to?(:iso8601)
    obj.iso8601(6)
  else
    obj.to_s
  end
end