When I code, I make quite intense use of "puts" statements for debugging. It allows me to see what happens in the server.
When the code is debugged, I use to remove these "puts" statements for I don't know what reason.
Is it a good idea or should I leave th开发者_如何学运维em instead to give more clarity to my server logs?
You should use the logger instead of puts
. Use this kind of statements:
Rails.logger.debug "DEBUG: #{self.inspect} #{caller(0).first}" if Rails.logger.debug?
If you want to see the debugging in the real-time (almost), just use the tail
command in another terminal window:
tail -F log/development.log | grep DEBUG
Then you do not need to remove these statements in production, and they will not degrade performance too much, because if logger.debug?
will prevent the (possibly expensive) construction of the message string.
Using standard output for debugging is usually a bad practice. In cases you need such debug, use the diagnostic STDERR
, as in:
STDERR.puts "DEBUG: xyzzy"
Most of the classes in Rails (models, controllers and views) have the method logger
, so if possible use it instead of the full Rails.logger
.
If you are using older versions of Rails, use the constant RAILS_DEFAULT_LOGGER
instead of Rails.logger
.
use the logger : http://guides.rubyonrails.org/debugging_rails_applications.html#the-logger
I use the rails_dt gem designed specifically to make such kind of debugging easier.
Using Rails.logger
or puts
directly is somewhat cumbersome, since it requires you to put a lot of decorative stuff (DEBUG
, ***
etc.) around debug messages to make them different from regular, useful messages.
Also, it's often difficult to find and defuse the debug output generated by Rails.logger
or puts
if the message doesn't appear to contain enough searchable characters.
rails_dt
prints the origin (file, line), so finding the position in code is easy. Also, you will never confuse DT.p
with anything, it clearly does debug output and nothing else.
Example:
DT.p "Hello, world!"
# Sent to console, Rails log, dedicated log and Web page, if configured.
[DT app/controllers/root_controller.rb:3] Hello, world!
Gem is available here.
精彩评论