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 registered 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:
a registered object based on its given namespace.
with the sole purpose of logging them. The log subscriber dispatches notifications to
ActiveSupport::LogSubscriber is an object set to consume ActiveSupport::Notifications
def attach_to(namespace, log_subscriber=new, notifier=ActiveSupport::Notifications)
def 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 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)
end of the returned String.
on the Highline implementation and will automatically append CLEAR to the
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
def flush_all!
def flush_all! flushable_loggers.each { |log| log.flush } end
def flushable_loggers
def flushable_loggers @@flushable_loggers ||= begin loggers = log_subscribers.map(&:logger) loggers.uniq! loggers.select { |l| l.respond_to?(:flush) } end end
def log_subscribers
def log_subscribers @@log_subscribers ||= [] end
def logger
def logger @logger ||= Rails.logger if defined?(Rails) end