Is there any way to automatically log everytime an ActiveRecord callback happens? It would help to trace through why certain things are happened when a record has several callbacks in place.
I'd like to see automated log message that indicate which messages are being called in response to which callbacks, e.g.: before_validation: calling update_capitalization
In Rails, callbacks are hooks provided by Active Record that allow methods to run before or after a create, update, or destroy action occurs to an object. Since it can be hard to remember all of them and what they do, here is a quick reference for all current Rails 5 Active Record callbacks.
Rails uses six different log levels: debug, info, warn, error, fatal, and unknown. Each level defines how much information your application will log: Debug: diagnostic information for developers and system administrators, including database calls or inspecting object attributes.
logger. debug , or in short logger. debug writes the parameter text to a log file. This log file is by default environment specific. If you are currently running rails in development environment then the log file in use is log/development.
In a Rails app, logs are stored under the /log folder. In development mode, the development. log file is used & you see log output on the terminal you're running rails server on.
For google and posterity (on Rails 3):
module CallbackTrace
def self.included kls
kls.send :alias_method_chain, :_compile_filter, :trace
end
def _compile_filter_with_trace filter
generated_code = _compile_filter_without_trace(filter)
return generated_code if filter.is_a?(Array)
method_name = generated_code.to_s.split(%r{\(|\s}).first
_klass = @klass
prelogger = ->{
Rails.logger.info("START [#{filter.class}](#{generated_code})")
Rails.logger.info("#{_klass} #{Time.now}")
if imethod=(_klass.instance_method(method_name) rescue nil)
begin
Rails.logger.info(imethod.source)
rescue MethodSource::SourceNotFoundError
Rails.logger.info("NO SOURCE FOR #{generated_code}")
end
else
Rails.logger.info("NO METHOD: #{method_name} for #{@klass}")
end
}
postlogger = ->{
Rails.logger.info("ENDED #{generated_code} #{Time.now}")
}
@klass.send :define_method, "prelogger_#{method_name}", &prelogger
@klass.send :define_method, "postlogger_#{method_name}", &postlogger
"(prelogger_#{method_name}; retval = retval = #{generated_code}; " +
"postlogger_#{method_name}; retval)"
end
end
ActiveSupport::Callbacks::Callback.send :include, CallbackTrace
I just wrote a gem for this.
# Gemfile
gem "rails-callback_log", group: [:development, :test]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With