Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print to log file without newline - Ruby on Rails

I have a logger to print to a file:

logger = Logger.new Rails.root.join 'log/my.log'

How can I print several dots in one line in different logger calls?

i.e., if I do

some_array.each do |el|
  logger.info '.'
  el.some_method
end

These dots will be printed in different lines.

like image 314
sites Avatar asked Mar 10 '14 23:03

sites


People also ask

How do you print without newline in Ruby?

Puts automatically adds a new line at the end of your message every time you use it. If you don't want a newline, then use print .

How do you print to the next line in Ruby?

We can also use "\n" ( newline character ) to print a new line whenever we want as used in most of the programming languages. Let's see an example. \n is the newline character. It prints a new line.

Which command is used to add a newline to the end of the output in Ruby?

"\n" is newline, '\n\ is literally backslash and n.

Where are logs stored in rails?

In a Rails app, logs are stored under the /log folder. In development mode, the development. log file is used & you see log output on the terminal you're running rails server on.


2 Answers

The << method lets you write messages without any formatting the log file.

For example:

require 'logger'

log = Logger.new "test.log"
log.info "Start"
5.times { log << "." }
log << "\n"
log.info "End"

Produces:

I, [2014-03-10T15:11:04.320495 #3410]  INFO -- : Start
.....
I, [2014-03-10T15:11:42.157131 #3410]  INFO -- : End

Unfortunately, this doesn't let you write to the same line as previous calls to log.info

like image 139
nullreff Avatar answered Sep 22 '22 11:09

nullreff


You can use Logger#<<(msg)

Dump given message to the log device without any formatting. If no log device exists, return nil.

some_array.each do |el|
  logger << '.'
  el.some_method
end
like image 42
Rafa Paez Avatar answered Sep 19 '22 11:09

Rafa Paez