Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Rails.logger printing to the console/stdout when running rspec?

Same as title: How to get Rails.logger printing to the console/stdout when running rspec? Eg.

Rails.logger.info "I WANT this to go to console/stdout when rspec is running"
puts "Like how the puts function works"

I still want Rails.logger to go to log/test.log too.

like image 921
s12chung Avatar asked Aug 02 '12 03:08

s12chung


3 Answers

For Rails 4.x the log level is configured a bit different than in Rails 3.x

Add this to config/environment/test.rb

# Enable stdout logger
config.logger = Logger.new(STDOUT)

# Set log level
config.log_level = :ERROR

The logger level is set on the logger instance from config.log_level at: https://github.com/rails/rails/blob/v4.2.4/railties/lib/rails/application/bootstrap.rb#L70

Environment variable

As a bonus, you can allow overwriting the log level using an environment variable with a default value like so:

# default :ERROR
config.log_level = ENV.fetch("LOG_LEVEL", "ERROR")

And then running tests from shell:

# Log level :INFO (the value is uppercased in bootstrap.rb)
$ LOG_LEVEL=info rake test

# Log level :ERROR
$ rake test
like image 183
Thomas B Homburg Avatar answered Nov 10 '22 05:11

Thomas B Homburg


For Rails 4, see this answer.

For Rails 3.x, configure a logger in config/environments/test.rb:

config.logger = Logger.new(STDOUT)
config.logger.level = Logger::ERROR

This will interleave any errors that are logged during testing to STDOUT. You may wish to route the output to STDERR or use a different log level instead.

Sending these messages to both the console and a log file requires something more robust than Ruby's built-in Logger class. The logging gem will do what you want. Add it to your Gemfile, then set up two appenders in config/environments/test.rb:

logger = Logging.logger['test']
logger.add_appenders(
    Logging.appenders.stdout,
    Logging.appenders.file('example.log')
)
logger.level = :info
config.logger = logger
like image 38
Phil Calvin Avatar answered Nov 10 '22 07:11

Phil Calvin


Tail the log as a background job (&) and it will interleave with rspec output.

tail -f log/test.log &
bundle exec rspec

When you're done with the log, bring it back into the foreground with fg and exit the tail with ctrl-c as usual.

like image 38
Jared Beck Avatar answered Nov 10 '22 05:11

Jared Beck