Class: Timber::Events::Custom

Inherits:
Timber::Event
  • Object
show all
Defined in:
lib/timber/events/custom.rb

Overview

Allows for custom events that aren’t covered elsewhere.

Custom events can be used to encode information about events that are central to your line of business like receiving credit card payments, saving a draft of a post, or changing a user’s password.

For examples of logging custom events see Logger.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes) ⇒ Custom

Instantiates a new custom event that can be logged. See Logger for examples on logging custom events.

Parameters:

  • attributes (Hash)

    the options to create a custom event with.

Options Hash (attributes):

  • :type (Symbol)

    required The custom event type. This should be in snake case. Example: ‘:my_custom_event`.

  • :message (String)

    required The message to be logged.

  • :data (Hash)

    A hash of JSON encodable data to be stored with the log line.



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/timber/events/custom.rb', line 25

def initialize(attributes)
  @type = attributes[:type] || raise(ArgumentError.new(":type is required"))
  @message = attributes[:message] || raise(ArgumentError.new(":message is required"))

  data = attributes[:data]

  if data.is_a?(Hash) && data[:time_ms].is_a?(Time)
    data[:time_ms] = Timer.duration_ms(data[:time_ms])
    @message << " in #{data[:time_ms]}ms"
  end

  @data = data
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



14
15
16
# File 'lib/timber/events/custom.rb', line 14

def data
  @data
end

#messageObject (readonly)

Returns the value of attribute message.



14
15
16
# File 'lib/timber/events/custom.rb', line 14

def message
  @message
end

#typeObject (readonly)

Returns the value of attribute type.



14
15
16
# File 'lib/timber/events/custom.rb', line 14

def type
  @type
end

Instance Method Details

#as_json(_options = {}) ⇒ Object

Builds a hash representation containing simple objects, suitable for serialization (JSON).



45
46
47
# File 'lib/timber/events/custom.rb', line 45

def as_json(_options = {})
  {:custom => to_hash}
end

#to_hashObject Also known as: to_h



39
40
41
# File 'lib/timber/events/custom.rb', line 39

def to_hash
  {Timber::Util::Object.try(type, :to_sym) => data}
end