简体   繁体   English

Ruby与记录器在同一行上进行多次打印

[英]Ruby multiple print on the same line with logger

I was using puts and print and \\r to rewrite something in the same line. 我正在使用putsprint\\r在同一行中重写某些内容。

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. 现在,我决定对任何日志输出使用内置的ruby记录器。

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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