I am new to rubymine. I have learned something about java by elipse. I want to see what happen in the process of rails.
def index
#must be active and logged in the last month
#users = User
.where("`is_active?` = true AND `last_sign_in_at` > DATE_SUB(NOW(), INTERVAL 6 MONTH)")
.reject{|u| u.biography.nil?}
.sort_by{|u| u.biography.last}
puts "haha"
end
I want to see puts "haha" in console. how can I see it?
Thank you very much!
Do you have a test for the above? if so you can type shift control r or type rspec in to terminal. otherwise just type the above into IRB. just type irb into terminal and press enter. Then enter the text and call index by typing index and hitting enter.
When you edit the configuration for debugging, you can use the menu to set these check-boxes which are by default un-checked in RubyMine 2017.1.1:
The best way is to use the logger:
# environment.rb
Rails.logger = Logger.new(STDOUT)
Rails.logger = Log4r::Logger.new("Application Log")
config.log_level = :debug
# your code
logger.debug "Hmmm... That went well."
Related
I was annoyed with having to cut way through ANSI sequences in a log on production server (log/production.log), so I added config.colorize_logging = false to config/environments/production.rb. But now when I run a console (bin/rails c), the output is not colorized as well. Why is it so? Is there a way to make logger use ANSI sequences when outputting to screen, and not use them when logging to a file?
UPD What I was able to figure out. When rails app starts, it creates logger to log into a file:
Rails.logger ||= config.logger || begin
path = config.paths["log"].first
unless File.exist? File.dirname path
FileUtils.mkdir_p File.dirname path
end
f = File.open path, 'a'
f.binmode
f.sync = config.autoflush_log # if true make sure every write flushes
logger = ActiveSupport::Logger.new f
logger.formatter = config.log_formatter
logger = ActiveSupport::TaggedLogging.new(logger)
logger
rescue StandardError
logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDERR))
logger.level = ActiveSupport::Logger::WARN
logger.warn(
"Rails Error: Unable to access log file. Please ensure that #{path} exists and is writable " +
"(ie, make it writable for user and group: chmod 0664 #{path}). " +
"The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
)
logger
end
And then attaches to it another logger to output messages to STDOUT:
def log_to_stdout
wrapped_app # touch the app so the logger is set up
console = ActiveSupport::Logger.new($stdout)
console.formatter = Rails.logger.formatter
console.level = Rails.logger.level
Rails.logger.extend(ActiveSupport::Logger.broadcast(console))
end
For some reason, breaking with byebug keyword at ActiveSupport::Logger#initialize never succeed when I ran ./bin/rails c.
UPD Okay, the culprit was spring, console (or should I say activerecord) creates its logger here:
console do |app|
require "active_record/railties/console_sandbox" if app.sandbox?
require "active_record/base"
console = ActiveSupport::Logger.new(STDERR)
Rails.logger.extend ActiveSupport::Logger.broadcast console
end
One way to switch colorized_logging on in console would be to set it explicitly to true as follows:
$ bin/rails c
:001 > Rails.application.config.colorize_logging
=> false
:002 > Rails.application.config.colorize_logging = true
=> true
:003 > Rails.application.config.colorize_logging
=> true
There might be a way to set this automatically every time the console is loaded by customizing the console with a .irbrc file
I am trying to output to the production log some logging that's happening in a function to which delay is being called on via delayed_job.
Example:
My controller
def create_something
#user = User.find(1)
#user.delay.do_something_crazy
end
My Model
def do_something_crazy
# some code
Rails.logger.info "Doing something crazy right now!"
end
The logging is not being output into my production log. Without delay, it does but with it seems to not?
Add initializer file delayed_jobs_settings.rb to config/initializers (unless you already have something like this for Delayed Jobs settings) and add this code:
Delayed::Worker.logger = Logger.new(Rails.root.join('log', 'dj.log'))
And it will save it to log/dj.log.
Or just
Delayed::Worker.logger = Rails.logger
for logging to default Rails log.
I'm trying to log the progress of my sideqik worker using tail -f log/development.log in development and heroku logs in production.
However, everything inside the worker and everything called by the worker does not get logged. In the code below, only TEST 1 gets logged.
How can I log everything inside the worker and the classes the worker calls?
# app/controllers/TasksController.rb
def import_data
Rails.logger.info "TEST 1" # shows up in development.log
DataImportWorker.perform_async
render "done"
end
# app/workers/DataImportWorker.rb
class DataImportWorker
include Sidekiq::Worker
def perform
Rails.logger.info "TEST 2" # does not show up in development.log
importer = Importer.new
importer.import_data
end
end
# app/controllers/services/Importer.rb
class Importer
def import_data
Rails.logger.info "TEST 3" # does not show up in development.log
end
end
Update
I still don't understand why Rails.logger.info or Sidekiq.logger.info don't log into the log stream. Got it working by replacing Rails.logger.info with puts.
There is a Sidekiq.logger and simply logger reference that you can use within your workers. The default should be to STDOUT and you should just direct your output in production to the log file path of your choice.
It works in rails 6:
# config/initializers/sidekiq.rb
Rails.logger = Sidekiq.logger
ActiveRecord::Base.logger = Sidekiq.logger
#migu, have you tried the below command in the config/initializer.rb ?
Rails.logger = Sidekiq::Logging.logger
I've found this solution here, it seems to work well.
Sidekiq uses the Ruby Logger class with default Log Level as INFO, and its settings are independent from Rails.
You may set the Sidekiq Log Level for the Logger used by Sidekiq in config/initializers/sidekiq.rb:
Sidekiq.configure_server do |config|
config.logger.level = Rails.logger.level
end
When I send an email with an attachment the data is logged in hex and fills up my whole log. Is there a way to disable logging of attachments?
I know I can disable mailer logging with config.action_mailer.logger = nil.
Unfortunately, the attachments are included in the logs if the logging level is set to :debug, the default level for non-production environments. This means that in production you should be fine, but your dev and staging environments could bloat during testing. You could turn down logging for your entire app (config.log_level = :info), but this is obviously less than ideal.
You can configure a custom logger:
config.action_mailer.logger = ActiveSupport::BufferedLogger.new("mailer.log")
config.action_mailer.logger.level = ActiveSupport::BufferedLogger::Severity::INFO
Rails 4
config.action_mailer.logger = ActiveSupport::Logger.new("mailer.log")
config.action_mailer.logger.level = ActiveSupport::Logger::Severity::INFO
This will split the log, but you can isolate the logging level change to the action mailer.
If you still want your log level to be debug, you can remove the attachments from the log output by overriding ActionMailer's LogSubscriber class. Look at the class in your actionmailer gem, and adjust accordingly. For my Rails 4.2.10 install, the relevant file is:
gems/actionmailer-4.2.10/lib/action_mailer/log_subscriber.rb
My module is:
module ActionMailer
class LogSubscriber < ActiveSupport::LogSubscriber
def deliver(event)
info do
recipients = Array(event.payload[:to]).join(', ')
"\nSent mail to #{recipients}, Subject: #{event.payload[:subject]}, on #{event.payload[:date]} (#{event.duration.round(1)}ms)"
end
debug { remove_attachments(event.payload[:mail]) }
end
def remove_attachments(message)
new_message = ''
skip = false
message.each_line do |line|
new_message << line unless skip
skip = true if line =~ /Content-Disposition: attachment;/
skip = false if skip && line =~ /----==_mimepart/
end
new_message
end
end
end
Save this to an .rb file anywhere under your app/ folder and it will be included.
in Application.rb you could try filtering the attachment parameter. I believe this should solve the issue, but I have not tested it myself
config.filter_parameters += [:attachment]
When Rails functions are asking for a translation (I18n.translate), I don't want to analyze their code in order to get the exact scopes etc.
How can I add a debug output into the console for every string that was asked for?
Examples:
I18n.t 'errors.messages.invalid', :scope => :active_record
# Translation for 'activerecord.errors.messages.invalid' (not) found
label(:post, :title)
# Translation for 'activerecord.attributes.post.title' not found
# Translation for 'views.labels.post.title' not found
This is not a very elegant solution, but it's worked for me. I've created an initialiser:
require 'i18n'
if (Rails.env.development? || Rails.env.test?) && ENV['DEBUG_TRANSLATION']
module I18n
class << self
def translate_with_debug(*args)
Rails.logger.debug "Translate : #{args.inspect}"
translate_without_debug(*args)
end
alias_method_chain :translate, :debug
end
end
end
You can then run commands like the following:
$ DEBUG_TRANSLATION=true rake cucumber
...and you'll see all the translations being attempted dumped to STDOUT. I don't consider this production code though, so I've kept it in a Gist, and not checked it into my main project source control at this stage.
Noddy, but it does the job.
Just a small change to put I18n debug messages in the log:
substitute this line:
puts "Translate: #{args.inspect}"
with
Rails.logger.debug "Translate : #{args.inspect}"