简体   繁体   中英

Ruby multiple print on the same line with logger

I was using puts and print and \\r to rewrite something in the same line.

For example:

    print "Fetching items...\r"

    #some loop here.
    print "Fetching items... #{i}/#{count}\r"
    #some loop here.

    puts "Fetching items... Done!"

Now I decide to use built-in ruby logger for any log output.

Is it possible to do the same thing with logger?

Just use custom formatter:

require 'logger'

class SimpleFormatter < Logger::Formatter

Format = "%s, [%s#%d] %5s -- %s: %s"

def call(severity, time, progname, msg)
  m = msg2str(msg)
  m << "\n" unless m[-1] == "\r"
  Format % [severity[0..0], format_datetime(time), $$, severity, progname,
    m]
end
end

logger = Logger.new(STDOUT)
logger.formatter = SimpleFormatter.new
logger.info("123\r"); sleep(2); logger.info("234\r"); sleep(2); logger.info("345")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM