John MacIntyre
John MacIntyre

Reputation: 13021

Why isn't 'logger.debug false' printing anything?

I'm having a problem with a boolean expression and when I did a logger.debug I had strange results, so I simplified my logging code to the following and was surprised not to see any 'false' being printed.

Logging code in my controller:

logger.debug 'true'
logger.debug true
logger.debug
logger.debug 'false'
logger.debug false
logger.debug
logger.debug '1 == 1'
logger.debug 1 == 1
logger.debug
logger.debug '1 == 0'
logger.debug 1 == 0

Which prints out the following

true
true

false


1 == 1
true

1 == 0

... ? I would expect to see false. When I run '1 == 0' or 'puts false' in the console I get false. Am I missing something?

Any ideas why isn't it printing the 'false'?

ruby version: 1.8.7-p352

rails version: 2.3.2

Upvotes: 3

Views: 600

Answers (2)

Dogbert
Dogbert

Reputation: 222090

Rails Logger uses || in the code before running .to_s, which fails for nil and false.

https://github.com/rails/rails/blob/master/activesupport/lib/active_support/buffered_logger.rb#L65

def add(severity, message = nil, progname = nil, &block)
  return if @level > severity
  message = (message || (block && block.call) || progname).to_s ## <- this line
  # If a newline is necessary then create a new message ending with a newline.
  # Ensures that the original message is not mutated.
  message = "#{message}\n" unless message[-1] == ?\n
  buffer << message
  auto_flush
  message
end

You can do this instead:

logger.debug( false.to_s)

Upvotes: 5

chrisrhoden
chrisrhoden

Reputation: 464

Logger has got a condition somewhere (if value), which fails for nil and false. You want logger.debug value.inspect.

Upvotes: 2

Related Questions