Class: Timber::Logger

Inherits:
Logger
  • Object
show all
Includes:
ActiveSupport::LoggerThreadSafeLevel, LoggerSilence
Defined in:
lib/timber/logger.rb

Overview

The Timber Logger behaves exactly like ‘::Logger`, except that it supports a transparent API for logging structured messages. It ensures your log messages are communicated properly with the Timber.io API.

To adhere to our no code debt / no lock-in promise, the Timber Logger will never deviate from the ‘::Logger` interface. That is, it will never add methods, or alter any method signatures. This ensures Timber can be removed without consequence.

Examples:

Basic example (the original ::Logger interface remains untouched):

logger.info "Payment rejected for customer #{customer_id}"

Using a Hash

# The :message key is required, the other additional key is your event type and data
# :type is the namespace used in timber for the :data
logger.info "Payment rejected", payment_rejected: {customer_id: customer_id, amount: 100}

Using a Struct (a simple, more structured way, to define events)

PaymentRejectedEvent = Struct.new(:customer_id, :amount, :reason) do
  # `#message` and `#type` are required, otherwise they will not be logged properly.
  # `#type` is the namespace used in timber for the struct data
  def message; "Payment rejected for #{customer_id}"; end
  def type; :payment_rejected; end
end
Logger.info PaymentRejectedEvent.new("abcd1234", 100, "Card expired")

Using typed Event classes

# Event implementation is left to you. Events should be simple classes.
# The only requirement is that it responds to #to_timber_event and return the
# appropriate Timber::Events::* type.
class Event
  def to_hash
    hash = {}
    instance_variables.each { |var| hash[var.to_s.delete("@")] = instance_variable_get(var) }
    hash
  end
  alias to_h to_hash

  def to_timber_event
    Timber::Events::Custom.new(type: type, message: message, data: to_hash)
  end

  def message; raise NotImplementedError.new; end
  def type; raise NotImplementedError.new; end
end

class PaymentRejectedEvent < Event
  attr_accessor :customer_id, :amount
  def initialize(customer_id, amount)
    @customer_id = customer_id
    @amount = amount
  end
  def message; "Payment rejected for customer #{customer_id}"; end
  def type; :payment_rejected_event; end
end

Logger.info PymentRejectedEvent.new("abcd1234", 100)

Defined Under Namespace

Classes: AugmentedFormatter, JSONFormatter, MessageOnlyFormatter, PassThroughFormatter

Instance Method Summary collapse

Constructor Details

#initialize(*io_devices) ⇒ Logger

Creates a new Timber::Logger instance where the passed argument is an IO device. That is, anything that responds to ‘#write` and `#close`.

Note, this method does not accept the same arguments as the standard Ruby ‘::Logger`. The Ruby `::Logger` accepts additional options controlling file rotation if the first argument is a file name. This is a design flaw that Timber does not assume. Logging to a file, or multiple IO devices is demonstrated in the examples below.

Examples:

Logging to STDOUT

logger = Timber::Logger.new(STDOUT)

Logging to the Timber HTTP device

http_device = Timber::LogDevices::HTTP.new("my-timber-api-key")
logger = Timber::Logger.new(http_device)

Logging to a file (with rotation)

file_device = Logger::LogDevice.new("path/to/file.log")
logger = Timber::Logger.new(file_device)

Logging to a file and the Timber HTTP device (multiple log devices)

http_device = Timber::LogDevices::HTTP.new("my-timber-api-key")
file_device = Logger::LogDevice.new("path/to/file.log")
logger = Timber::Logger.new(http_device, file_device)


211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/timber/logger.rb', line 211

def initialize(*io_devices)
  io_device = \
    if io_devices.size == 0
      raise ArgumentError.new("At least one IO device must be provided when instantiating " +
        "a Timber::Logger. Ex: Timber::Logger.new(STDOUT).")
    elsif io_devices.size > 1
      LogDevices::Multi.new(io_devices)
    else
      io_devices.first
    end

  super(io_device)

  # Ensure we sync STDOUT to avoid buffering
  if io_device.respond_to?(:"sync=")
    io_device.sync = true
  end

  # Set the default formatter. The formatter cannot be set during
  # initialization, and can be changed with #formatter=.
  if io_device.is_a?(LogDevices::HTTP)
    self.formatter = PassThroughFormatter.new
  elsif Config.instance.development? || Config.instance.test?
    self.formatter = MessageOnlyFormatter.new
  else
    self.formatter = AugmentedFormatter.new
  end

  self.level = environment_level

  after_initialize if respond_to?(:after_initialize)

  Timber::Config.instance.debug { "Timber::Logger instantiated, level: #{level}, formatter: #{formatter.class}" }

  @initialized = true
end

Instance Method Details

#add(severity, message = nil, progname = nil, &block) ⇒ Object

Patch to ensure that the #level method is used instead of ‘@level`. This is required because of Rails’ monkey patching on Logger via ‘::LoggerSilence`.



276
277
278
279
# File 'lib/timber/logger.rb', line 276

def add(severity, message = nil, progname = nil, &block)
  return true if @logdev.nil? || (severity || UNKNOWN) < level
  super
end

#formatter=(value) ⇒ Object

Note:

The formatter cannot be changed if you are using the HTTP logger backend.

Sets a new formatted on the logger.



251
252
253
254
255
256
257
258
259
# File 'lib/timber/logger.rb', line 251

def formatter=(value)
  if @initialized && @logdev && @logdev.dev.is_a?(Timber::LogDevices::HTTP) && !value.is_a?(PassThroughFormatter)
    raise ArgumentError.new("The formatter cannot be changed when using the " +
      "Timber::LogDevices::HTTP log device. The PassThroughFormatter must be used for proper " +
      "delivery.")
  end

  super
end

#level=(value) ⇒ Object



261
262
263
264
265
266
# File 'lib/timber/logger.rb', line 261

def level=(value)
  if value.is_a?(Symbol)
    value = level_from_symbol(value)
  end
  super
end

#with_context(context, &block) ⇒ Object

Convenience method for adding context. Please see Timber::Logger.{Timber{Timber::CurrentContext{Timber::CurrentContext.with} for a more detailed description and examples.



270
271
272
# File 'lib/timber/logger.rb', line 270

def with_context(context, &block)
  Timber::CurrentContext.with(context, &block)
end