Class: Timber::Contexts::Custom

Inherits:
Timber::Context
  • Object
show all
Defined in:
lib/timber/contexts/custom.rb

Overview

Custom contexts allow you to add application specific context not covered elsewhere. Any data added this way will be included in your logs. A good example is worker job IDs. When processing a job you might add the job ID to the context, allowing you to view all logs generated while processing that job, not just the logs that contain the ID.

Note in the example below all custom contexts must contain a root key. This is to ensure attribute names and types never clash across your contexts. It gives you much cleaner pallete to organize your data on.

Examples:

Adding a custom context

logger.with_context(build: {version: "1.0.0"}) do
  # anything logged here will have the custom context above
  # when this block exits the context will no longer be included
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes) ⇒ Custom

Returns a new instance of Custom.



26
27
28
29
# File 'lib/timber/contexts/custom.rb', line 26

def initialize(attributes)
  @type = Timber::Util::Object.try(attributes[:type], :to_sym) || raise(ArgumentError.new(":type is required"))
  @data = attributes[:data] || raise(ArgumentError.new(":data is required"))
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



24
25
26
# File 'lib/timber/contexts/custom.rb', line 24

def data
  @data
end

#typeObject (readonly)

Returns the value of attribute type.



24
25
26
# File 'lib/timber/contexts/custom.rb', line 24

def type
  @type
end

Instance Method Details

#as_json(options = {}) ⇒ Object

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



32
33
34
# File 'lib/timber/contexts/custom.rb', line 32

def as_json(options = {})
  {type => data}
end