logger.debug not writing to log file in Rails - ruby-on-rails

I am trying to debug a model in Rails so I'm using this code:
logger.debug('asasd')
However, I'm tailing the log file development.log but I'm not seeing it add to this file.
I am certain this module is being run
I have confirmed that runtime errors are logging to this file, and I see them when I tail.
How do I get this to work?

Make sure that you have set the log level to debug in environments/appropriate_env_file.rb:
config.log_level = :debug
and also make sure you are tailing the correct log file based on the environment you are running against.

You could attempt to call flush on the logger to force it to write to this file. Usually this would happen after every request:
logger.debug("asasd")
logger.flush
There's also the auto_flushing setting on the Rails.logger instance itself:
Rails.logger.auto_flushing = true
This will make the call to logger.flush unnecessary, as Rails will automatically flush the buffered output to the log file whenever it is written to.

Related

Rails Logs: Only show Create, Update, and Destroy SQL statements in Logs and nothing else

I only want to see CREATE/UPDATE/DESTROY-related sql statements in the logs. I do not want any READ-related statements, caches, or any other information displayed in the logs because it is making it tough to sift through.
Currently within app/config/environments/production.rb I have the following configuration set which shows way too much in the logs:
config.log_level = :debug
The default config for production shows too little information. It ignores all the sql statements I want to see:
# shows too little information
config.log_level = :info
Is there a configuration setting in rails to have the logs output only the information I want to see? If not: how might I do this?
You can disable logging of ActiveRecord database queries by setting the log_level to :info.
Then use Rails' ActiveSupport::Instrumentation and subscribe to the sql.active_record event.
Just add the following code into an initializer:
# in `config/initializers/query_logger.rb`
class QueryLogger
def call(name, started, finished, unique_id, payload)
query = payload[:sql]
Rails.logger.info("SQL Query: #{query}") unless query.start_with?('SELECT')
end
end
ActiveSupport::Notifications.subscribe('sql.active_record', QueryLogger.new)

Rails 4 - Should I place logger/debug messages inside a block Rails.env.development?

I am using inside a controller a logger message:
logger.debug "Here is the resulting object find_by_sql outputs: #{#deal}"
Should I use
if Rails.env.development?
logger.debug "Here is the resulting object find_by_sql outputs: #{#deal}"
end
Is it generally a good practice to put the logger message inside a Rails.dev block? I don't want to slow even a little little bit the app so the fact i add a if/end block will slow the app.
Letting it without any restriction to the dev mode would compromise the information security?
There's no need to do that with if statements. It's already controlled by log_level of the environment
In your config/environments/development.rb
config.log_level = :debug
But if you put this into config/environments/production.rb (default value, btw), you won't see any debug messages in the production log.
config.log_level = :warn
If you want to temporarily increase verbosity of production logs (for debugging or whatever), change log_level and redeploy. Do your troubleshooting and then rollback the app when you're done. Easier than touching Rails.env checks all over the codebase, isn't it?

Joining separate log to main Rails development log

This is the reverse of the question I have seen several times elsewhere, in which someone wants to see how to create an another, separate Rails log from the main development log. For some reason, my Rails app is logging my DelayedJob gem's activity to a separate log (delayed_job.log), but I want it to log to the main development.log file. I am using the Workless gem and NewRelic as well, should this be potentially relevant (although I experimented on this by removing NewRelic, and the issue still remained).
I'm not clear on how this happened. However, I was having some trouble earlier with seeing SQL insertions and deletions in my log, and another user kindly suggested that I use the following in an initializer file:
if defined?(Rails) && !Rails.env.nil?
logger = Logger.new(STDOUT)
ActiveRecord::Base.logger = logger
ActiveResource::Base.logger = logger
end
Once I did this, I saw the SQL statements, but no longer saw the DelayedJob information in the main development log.
So my question is: How can I make sure that DelayedJob activity logs to the main development log? I don't mind if it also logs to a separate log, but the important thing is that I see its activity in my Mac's console.
Please let me know if you'd like more code from my app - I'd be happy to provide it. Much thanks from a Rails newbie.
Try adding the following line to config/initializers/delayed_job_config.rb
Delayed::Worker.logger = Logger.new(STDOUT)
I finally got this to work. All thanks to Seamus Abshere's answer to the question here. I put what he posted below in an initializer file. This got delayed_job to log to my development.rb file (huzzah!).
However, delayed_job still isn't logging into my console (for reasons I still don't understand). I solved that by opening a new console tab and entering tail -f log/development.log.
Different from what Seamus wrote, though, auto-flushing=true is deprecated in Rails 4 and my Heroku app crashed. I resolved this by removing it from my initializer file and placing it in my environments/development.rb file as config.autoflush_log = true. However, I found that neither of the two types of flushing were necessary to make this work.
Here is his code (without the auto-flushing):
file_handle = File.open("log/#{Rails.env}_delayed_jobs.log", (File::WRONLY | File::APPEND | File::CREAT))
# Be paranoid about syncing
file_handle.sync = true
# Hack the existing Rails.logger object to use our new file handle
Rails.logger.instance_variable_set :#log, file_handle
# Calls to Rails.logger go to the same object as Delayed::Worker.logger
Delayed::Worker.logger = Rails.logger
If the above code doesn't work, try replacing Rails.logger with RAILS_DEFAULT_LOGGER.

Rails full error page not showing for view errors

I have a view named new.html.erb with the following code:
<%= some_non_existent_thing.imaginary_method %>
Now, I only see one simple 500 error page, like that:
500 Internal Server Error
If you are the administrator of this website, then please read this web application's log file and/or the web server's log file to find out what went wrong.
Shouldn't I see a pretty formatted page with some information about the exception?
I'm not sure I miss something here, but I believe rails used to show the full error page in development environment when there is something wrong in the view.
Are you sure that you are running the development environment? Check that RAILS_ENV=development or that you are running rails server -e development.
Then check your development.rb file, you should have the following line in it
config.consider_all_requests_local = true
If you happen to have an exception inside an exception, Rails has a middleware that catches it and returns a FAILSAFE_RESPONSE with the following copy:
500 Internal Server Error
If you are the administrator of this website, then please read this web application's log file and/or the web server's log file to find out what went wrong.
A nice way to troubleshoot this is to compare your custom error code with the sample code provided in the Rails 4.2.0 guides.
I'm pointing to that particular version because that whole section was removed in the Rails 5.0.0 guides.
Ideally, you should keep your error views, layout, and controller as free of logic as possible, to avoid running into this issue.
Firstly, as Anton mentions in the answer below, confirm that your config/environments/development.rb has:
config.consider_all_requests_local = true
and that you are running the server in development mode.
I had ensured the above and still observed the error.
This happened in my case, because my logger had some errors. I was using a custom log formatter, which used the String#% method to format the log. % seems to be very buggy and leads to all these weird errors. I figured this one out by adding a debugger line to the controller method and stepping through into the implicit render function call. It hit the bug and reported it as a malformed format string error.
This was the log formatter I was using before, which caused the bugs [I had added it to an initializer file]:
class Logger::SimpleFormatter
def call(severity, time, progname, msg)
"%-7s #{msg}\n" % severity
end
end
These modifications fixed the bug:
class Logger::SimpleFormatter
def call(severity, time, progname, msg)
severity_prefix = "[#{severity}]".ljust(7)
"#{severity_prefix} #{msg}\n"
end
end
This happens if the code is not compilable, for example if you have an if statement missing an end.

Ruby on rails log file size too large

I stumbled to learn that my rails3.1 log file is super large, around 21mb.
Is this, in terms of size normal? What the log file would like in the production environment?
Besides, can I get rid of the log?thanks
The log folder of your Rails application holds three log files corresponding to each of the standard environments. Log files can grow very large over time. A rake task is provided to allow the easy clearing of the log files.
rake log:clear
# Truncates all *.log files in log/ to zero bytes
# Specify which logs with LOGS=test,development,production
you can just delete the file!
Rails will create a new log if one doesn't exist.
Obviously save / backup the file if it's important, but usually it's not.
You can also zip the backuped up file (and then delete the source) if you want to keep it on the same drive but still save space.
To automatically rotate log files (the best long-term solution) use log rotate as described here:
Ruby on Rails production log rotation
then you can set it and forget it!
To actually change what gets logged see:
http://dennisreimann.de/blog/silencing-the-rails-log-on-a-per-action-basis/
According to the documentation, if you want to limit the size of the log folder, put this in your 'development.rb'-file:
config.logger = ActiveSupport::Logger.new(config.paths['log'].first, 1, 50 * 1024 * 1024)
With this, your log files will never grow bigger than 50Mb. You can change the size to your own preference. The ‘1’ in the second parameter means that 1 historic log file will be kept, so you’ll have up to 100Mb of logs – the current log and the previous chunk of 50Mb.
I automatically clear the logs in development on each server start with config/initializers/clear_development_log.rb:
if Rails.env.development?
`rake log:clear`
end
You may want to use logrotate. Have a look at the answer to this question: Ruby on Rails production log rotation.
Yes, You can using syntax like this:
config.logger = ActiveSupport::Logger.new(config.log_file, num_of_file_to_keep, num_of_MB*1024*1024)
Example:
config.logger = ActiveSupport::Logger.new(config.log_file, 2, 20*1024*1024)
It not only using for Rails log, you can using log file of any services run with rails, such as: rpush log, ...
config.logger = ActiveSupport::Logger.new(nil) does the trick and completely disables logging to a file (console output is preserved).
A fair compromise, in an initializer:
Rake::Task['log:clear'].invoke if Rails.env.development? || Rails.env.test?
If you don't like waiting for rake log:clear to load its environment and only want to clear one log on the fly, you can do the following:
cat /dev/null > log/mylog.log # Or whatever your log's name is
(This allows the log to stay online while the app is running, whereas rm log/mylog.log would require restarting the app.)

Resources