Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 414
user1479978 Avatar asked Apr 30 '14 20:04

user1479978


People also ask

How do I display a SQL query?

The DISPLAY command must be placed immediately after the query statement on which you want it to take effect. For example: SELECT pno, pname FROM part WHERE color='BLUE'; DISPLAY; When the system encounters this DISPLAY command, it displays the Result window containing the part number and name for all blue parts.

Can you console log in rails?

One of the best tools in a rails developers arsenal is the rails console, being extremely useful for brainstorming, debugging, and testing. Having it log active record queries directly to the console can improve readability and convenience over looking through the development logs to see what SQL queries have been run.

How do I use logger in Ruby on Rails?

To write in the current log use the logger. (debug|info|warn|error|fatal|unknown) method from within a controller, model, or mailer: logger. debug "Person attributes hash: #{@person.

What is the log to check for errors in Rails?

Rails uses six different log levels: debug, info, warn, error, fatal, and unknown. Each level defines how much information your application will log: Debug: diagnostic information for developers and system administrators, including database calls or inspecting object attributes.


2 Answers

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')
like image 79
jimagic Avatar answered Oct 17 '22 03:10

jimagic


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

 config.log_level = :debug
like image 7
ilgam Avatar answered Oct 17 '22 03:10

ilgam