使用Rails 4在日志中显示SQL查询

时间:2023-01-19 22:02:13

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".

我在Ubuntu 14.04上通过我的终端“终结者”和我的shell“Fish Shell”在Ruby 2.1和Thin 1.6.2上使用Rails 4.0.4。

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.

当我在开发模式下启动Rails服务器时,我的日志中没有SQL查询,只加载了JS和HTML文件。

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)

3 个解决方案

#1


22  

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

rails控制台永远不会写入日志文件,但您可以非常轻松地实现它,例如,如果您在启动rails控制台后执行以下操作

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:

rails会将所有SQL语句记录到stdout,从而在终端中显示它们。由于Logger.new接受任何流作为第一个参数,你可以让它写入rails development.log:

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

#2


4  

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.

这似乎也使得日志记录不再具有丑陋的时间戳。

#3


3  

Set config.log_level in config/environments/development.rb to :debug and restart your local server, console:

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

 config.log_level = :debug

#1


22  

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

rails控制台永远不会写入日志文件,但您可以非常轻松地实现它,例如,如果您在启动rails控制台后执行以下操作

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:

rails会将所有SQL语句记录到stdout,从而在终端中显示它们。由于Logger.new接受任何流作为第一个参数,你可以让它写入rails development.log:

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

#2


4  

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.

这似乎也使得日志记录不再具有丑陋的时间戳。

#3


3  

Set config.log_level in config/environments/development.rb to :debug and restart your local server, console:

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

 config.log_level = :debug