简体   繁体   中英

Display SQL queries in log with Rails 4

I'm using Rails 4.0.4 with Ruby 2.1 and Thin 1.6.2 on Ubuntu 14.04 through my terminal "Terminator" and my shell "Fish Shell".

When I'm launching my Rails server in development mode I don't have the SQL queries in my logs only the JS and HTML files are loaded.

I'm searching for something like that:

User Load (3.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 3 ORDER BY "users"."id" ASC LIMIT 1
(2.0ms)  SELECT COUNT(*) FROM "users" WHERE (driver_register_state_cd = -2)

the rails console never writes to the log file, but you can achieve it quite easily, for example, if you execute following after starting the rails console

ActiveRecord::Base.logger = Logger.new STDOUT

rails will log all SQL statements to stdout, thus display them in your terminal. and since Logger.new accepts any stream as first argument, you could just let it write to the rails development.log:

ActiveRecord::Base.logger = Logger.new File.open('log/development.log', 'a')

I got what I wanted by creating an initializer file:

# initializers/sql_logging.rb
ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT)

This also seems to keep the logging from having the ugly timestamps prepended.

将config / environments / development.rb中的config.log_level设置为:debug并重新启动本地服务器,console:

 config.log_level = :debug

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM