Module: JsonLogging::Helpers

Defined in:
lib/json_logging/helpers.rb

Constant Summary collapse

ISO8601_MICROSECOND_UTC_PATTERN =
/\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z\z/

Class Method Summary collapse

Class Method Details

.current_timeObject

Get current time, using Time.zone if available, otherwise Time.now



27
28
29
30
31
32
33
# File 'lib/json_logging/helpers.rb', line 27

def current_time
  if defined?(Time.zone) && Time.zone
    Time.zone.now
  else
    Time.now
  end
end

.current_timestampObject



14
15
16
# File 'lib/json_logging/helpers.rb', line 14

def current_timestamp
  format_timestamp(current_time)
end

.format_timestamp(time) ⇒ Object



18
19
20
# File 'lib/json_logging/helpers.rb', line 18

def format_timestamp(time)
  time.utc.iso8601(6)
end

.iso8601_microsecond_utc?(timestamp) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/json_logging/helpers.rb', line 22

def iso8601_microsecond_utc?(timestamp)
  timestamp.is_a?(String) && timestamp.match?(ISO8601_MICROSECOND_UTC_PATTERN)
end

.normalize_timestamp(timestamp) ⇒ Object

Normalize timestamp to ISO8601 with microseconds



8
9
10
11
12
# File 'lib/json_logging/helpers.rb', line 8

def normalize_timestamp(timestamp)
  return timestamp if iso8601_microsecond_utc?(timestamp)

  format_timestamp(timestamp || current_time)
end

.safe_string(obj) ⇒ Object

Safely convert object to string, never raises



36
37
38
39
40
# File 'lib/json_logging/helpers.rb', line 36

def safe_string(obj)
  obj.to_s
rescue
  "<unprintable>"
end