class Motion::LogHelper

Constants

BACKTRACE_FRAMES
DEFAULT_TAG

Attributes

logger[R]
tag[R]

Public Class Methods

for_channel(channel, logger: channel.connection.logger) click to toggle source
# File lib/motion/log_helper.rb, line 13
def self.for_channel(channel, logger: channel.connection.logger)
  new(logger: logger, tag: DEFAULT_TAG)
end
for_component(component, logger: nil) click to toggle source
# File lib/motion/log_helper.rb, line 17
def self.for_component(component, logger: nil)
  new(logger: logger, tag: "#{component.class}:#{component.object_id}")
end
new(logger: nil, tag: nil) click to toggle source
# File lib/motion/log_helper.rb, line 23
def initialize(logger: nil, tag: nil)
  @logger = logger || Rails.logger
  @tag = tag || DEFAULT_TAG
end

Public Instance Methods

error(message, error: nil) click to toggle source
# File lib/motion/log_helper.rb, line 28
def error(message, error: nil)
  error_info = error ? ":\n#{indent(format_exception(error))}" : ""

  logger.error("[#{tag}] #{message}#{error_info}")

  Motion.notify_error(error, message)
end
for_component(component) click to toggle source
# File lib/motion/log_helper.rb, line 50
def for_component(component)
  self.class.for_component(component, logger: logger)
end
info(message) click to toggle source
# File lib/motion/log_helper.rb, line 36
def info(message)
  logger.info("[#{tag}] #{message}")
end
timing(message) { || ... } click to toggle source
# File lib/motion/log_helper.rb, line 40
def timing(message)
  start_time = Time.now
  result = yield
  end_time = Time.now

  info("#{message} (in #{format_duration(end_time - start_time)})")

  result
end

Private Instance Methods

format_duration(duration) click to toggle source
# File lib/motion/log_helper.rb, line 62
def format_duration(duration)
  duration_ms = duration * 1000

  if duration_ms < 0.1
    "less than 0.1ms"
  else
    "#{duration_ms.round(1)}ms"
  end
end
format_exception(exception) click to toggle source
# File lib/motion/log_helper.rb, line 56
def format_exception(exception)
  frames = exception.backtrace.first(BACKTRACE_FRAMES).join("\n")

  "#{exception.class}: #{exception}\n#{indent(frames)}"
end
indent(string) click to toggle source
# File lib/motion/log_helper.rb, line 72
def indent(string)
  string.indent(1, "\t")
end