Rails puts to console - ruby-on-rails

In my Rails app, there are some cases where code is being outputted with the puts command (for debugging purposes). Is there anyway to follow this output in the rails console (with the rails c command)? Or is there any other way to debug/view logs in the rails console?
Thanks!

For debugging, use Rails.logger instead of puts. For example:
Rails.logger.info "Some debugging info"
This will be logged to a log file in rails_app_root/log directory. If you are running in development environment locally, it will be logged to rails_app/log/development.log file.
Now, to see the log as they come in you can use tail command, like this:
tail -f log/development.log
Hope it helps.

Rails.logger is the best solution,one more think i want to add,if you want separate log file you could use like this
def read(args)
unless args.blank?
cache_key= self.get_cache_key(args)
end
logger = Logger.new("#{Rails.root}/log/cache_read.log")
logger.error("cache read scope == #{cache_key.to_s}")
end
so cache_read.log file having only this method log only.

Related

How can I print data using the puts statement to development.log file in rails?

When I write Print statements those are not getting printed in the log/development.log file when I'm working in development mode. How can I make puts statement work in development.log file in rails?
Example (from inside of an controller):
def some_method
pi = 3.1514
logger.debug "Debug message"
logger.info "Info message"
logger.info "PI equals #{pi}"
end
There are 5 types of messages: DEBUG, INFO, WARN, ERROR, FATAL
I recommend reading this chapter from Rails Guides: 2.3 Sending Messages
To write to your log file you should use
logger.debug "Anything"
Please note that the file (development, production, test) depends on the environment you are actually using

How to run code automatically when launching a Rails console?

Let's say I wanted a greeting every time the Rails console comes up:
Scotts-MBP-4:ucode scott$ rails c
Loading development environment (Rails 4.2.1)
Hello there! I'm a custom greeting
2.1.5 :001 >
Where would I put the puts 'Hello there! I\'m a custom greeting' statement?
Another Stackoverflow answer suggested, and I've read this elsewhere too, that I can put that in an initializer like this:
# config/initializers/console_greeting.rb
if defined?(Rails::Console)
puts 'Hello there! I\'m a custom greeting'
end
That doesn't work for me though :(. Even without the if defined?(Rails::Console) I still don't get output. Seems like initializers are not run when I enter a console, despite what others suggest.
I use ~/.irbrc for similar purposes (I require a gem in each console session). For example, my .irbrc
if (defined? Rails)
# Rails specific
end
# common for all irb sessions
You could use your project name to limit executing code to only one project's console:
if (defined? Rails) && (defined? YourProject)
# code goes here
end
The following will work in Rails 6:
Just pass a block to Rails.application.console, e.g
# config/initializers/custom_console_message.rb
if Rails.env.production?
Rails.application.console do
puts "Custom message here"
end
end
Now when starting the rails production console, the custom message will be printed. This code will not be executed when you start rails server.
Remove the if Rails.env.production? if you want this to run in all environments.

How to debug using rails console and puts in application

I want to get some lines printed in irb opened through rails console. I have seen a lot of SO questions of how to achieve it. But I get nothing in the irb.
below is the code--
def show
puts 'in show method'
#post = Feed.find_by_id params[:id]
puts #post.inspect
redirect_to root_path unless #post.present?
end
now I have opened server by command rails server. Also, In another terminal I gave the command rails console, it opened the irb prompt. when in browser I run localhost:3000/posts/82 it gives the correct post, but nothing is shown in the console. What step am I missing? I want to print something in the console when a particular method is called.
Best way to debug is to use the debugger command.
If you are using ruby 2.0 or above, you have to use the gem 'byebug' and if you are using 1.9 or below, then gem ruby-debug
then, when you run your server in development mode, your server will stop when it reaches the debugger allowing you to see your objects' state and modify them (much better than simply using puts
The program will stop in the same window that your server runs.
Some basic commands:
c continues the execution until next debugger is found
n runs the next command. If it is a function executes the
function
s step into the next command. If it is a
function, you will get into the function and see the variables
display expression on every step display the result of the
expression you write (very useful when debugging loops)
undisplay expression_number stops displaying the expresion
display shows all the expressions being displayed
list Displays the source code being executed
help shows the available commands help
command_name shows detailed info about a command
More info about debugging: http://guides.rubyonrails.org/debugging_rails_applications.html
The puts 'in show method' in line 2 won't show the output in rails console. Instead it shows the output in the same terminal where you did rails server. They might be lost with so much of output, so try to find it there itself.
Use Rails.logger.debug "in show method" etc.
In the second tab in terminal tail log/development.log like this
$ cd rails_app_root
$ tail -f log/development.log
or
$ cd rails_app_root
$ less +F log/development.log
There you will find all the output from the console.
Try to use Rails.logger
Rails.logger.info "Some debugging info I want to see in my
development log.------#{#post.inspect}"
It will print #post value in log file.
I am a big fan of puts debugging. e.g;
def index
method = Kernel.instance_method(:method)
p method.bind(request).call(:headers).source_location
#users = User.all
end
The above snippet helps you find where the method is implemented:
Processing by UsersController#index as */*
["/Users/aaron/git/rails/actionpack/lib/action_dispatch/http/request.rb", 201]
You can find more cool puts debugging here.

Rails: How to write to a custom log file from within a rake task in production mode?

I'm trying to write to my log files while running a rake task. It works fine in development mode, but as soon as I switch to the production environment, nothing is written to the log files.
I read here
How do I use a custom log for my rake tasks in Ruby on Rails?
that this is the normal behavior and also found a #wontfix ticket in lighthouse.
My question: Is there a way to output, what's going on while my rake task is running? It performs some crawling and runs for hours. I would prefer if the output went in a specific log file like /log/crawler.log
Right now I'm just using this command to write to the log files:
ActiveRecord::Base.logger.info "Log Text"
Thanks!
The problem you are having is that rails ignores 'info' level logs in production mode.
I'd recommend reading this: http://www.ruby-doc.org/stdlib/libdoc/logger/rdoc/classes/Logger.html
and creating your own logger:
logger = Logger.new('logfile.log')
logger.info "Something happened"
You can make a new logger with Logger.new("file.log") and then call it's methods like this.
task :import_stuff => :environment do
require 'csv'
l = Logger.new("stuff.log")
csv_file = "#{RAILS_ROOT}/stuff.csv"
CSV.open(csv_file, 'r') do |row|
l.info row[1]
end
end
Maybe you need to write out the buffer where you need it:
logger.flush
or you can turn on auto flushing:
task :foo => :environment do
Rails.logger.auto_flushing = 1
Rails.logger.info "bar"
end

"Printf" testing in Rails

I'm new to Rails and I'm aware it has things such as unit-testing built in. But I'm interested in doing some more simple tests that are equivalent to your "printf" in C. So I'm testing a login page I've written and want to trace the code to see what each line like my find methods are returning. I try outputting with "puts" but I don't get anything in the command-line.
I use puts statements all the time as well as the ruby debugger! It's great.
In rails you can do a couple things. I put "puts" in my code and when I run script/server at the command line, the output appears in my Terminal.app. I am running a Mac, but I am sure that there is a similar way to trace the activity of your app on your platform of choice.
The other option is to use the logger statement. you can call
logger.debug("My #{variable}")
and find these statements right in your log/development.log file.
Also, if you are running on a *nix system, you can use the "tail" command to trace the last statement written to your log one at a time.
tail -f log/development.log
This way you could write your statements and see them as they are happening. There are several levels of logging:
logger.warn
logger.info
logger.debug
logger.fatal
each environment (development, testing, production) will determine what "level" of logging will be called, so you may write log statements willy nilly with logger.debug while in development, but those log statements won't be written when you deploy based on the default log levels.
User something like this:
logger.info "method called with #{params.inspect}"
(you can put any variable inside the #{})
Once you're having fun with that, check out ./script/console and ruby-debug
Are you familiar with ruby-debug?
Install the ruby-debug gem.
Start your server with the -u option.
script/server -u
Put a debugger statement in your code where you want to stop.
You will have console access to your variables as well as the ability to step through your code.
Check the ruby-debug documentation for more details.
I've done this before - with Passenger, you don't have script/server's output, so I wrote this:
# extras/sexy_logging.rb
module SexyLogging
def log(text)
return true if RAILS_ENV == 'production'
string = "\e[0;32mLog:\e[m #{text}"
(100 - string.length).times do
string << ' '
end
string << "(#{caller.first})"
logger.debug string
end
end
ActiveRecord::Base.send :include, SexyLogging
ActionController::Base.send :include, SexyLogging
Then you can write
log variable
or
log 'Testing user'
tail -f log/development.log |grep Log:
and only see what you're logging, line by line and with colours.

Resources