class ActiveSupport::LogSubscriber
a Rails environment.
all logs when the request finishes (via action_dispatch.callback notification) in
Log subscriber also has some helpers to deal with logging and automatically flushes
the sql method.
it will properly dispatch the event (ActiveSupport::Notifications::Event) to
After configured, whenever a “sql.active_record” notification is published,
the line above should be called after your ActiveRecord::LogSubscriber definition.
Since we need to know all instance methods before attaching the log subscriber,
ActiveRecord::LogSubscriber.attach_to :active_record
And it’s finally registed as:
end
end
end
“#{event.payload} (#{event.duration}) #{event.payload}”
def sql(event)
class LogSubscriber < ActiveSupport::LogSubscriber
module ActiveRecord
An example would be Active Record log subscriber responsible for logging queries:
regirested object based on its given namespace.
with solely purpose of logging. The log subscriber dispatches notifications to a
ActiveSupport::LogSubscriber is an object set to consume ActiveSupport::Notifications
def self.attach_to(namespace, log_subscriber=new, notifier=ActiveSupport::Notifications)
def self.attach_to(namespace, log_subscriber=new, notifier=ActiveSupport::Notifications) log_subscribers << log_subscriber @@flushable_loggers = nil log_subscriber.public_methods(false).each do |event| next if 'call' == event.to_s notifier.subscribe("#{event}.#{namespace}", log_subscriber) end end
def self.flush_all!
def self.flush_all! flushable_loggers.each(&:flush) end
def self.flushable_loggers
def self.flushable_loggers @@flushable_loggers ||= begin loggers = log_subscribers.map(&:logger) loggers.uniq! loggers.select { |l| l.respond_to?(:flush) } end end
def self.log_subscribers
def self.log_subscribers @@log_subscribers ||= [] end
def self.logger
def self.logger @logger ||= Rails.logger if defined?(Rails) end
def call(message, *args)
def call(message, *args) return unless logger method = message.split('.').first begin send(method, ActiveSupport::Notifications::Event.new(message, *args)) rescue Exception => e logger.error "Could not log #{message.inspect} event. #{e.class}: #{e.message}" end end
def color(text, color, bold=false)
of the returned String.
on Highline implementation and it automatically appends CLEAR to the end
option is set to true, it also adds bold to the string. This is based
Set color by using a string or one of the defined constants. If a third
def color(text, color, bold=false) return text unless colorize_logging color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol) bold = bold ? BOLD : "" "#{bold}#{color}#{text}#{CLEAR}" end