如何格式化ruby logger?

时间:2013-01-17 15:18:57

标签: ruby logging

如何格式化ruby记录器?

2 个答案:

答案 0 :(得分:52)

logger = Logger.new('nice.log')

logger.formatter = proc do |severity, datetime, progname, msg|
   "NICE: #{msg}\n"
end

logger.info("I like cheese.")

# nice.log:
NICE: I like cheese.

答案 1 :(得分:29)

如果您只想格式化时间,可以使用datetime_format和标准format specification轻松完成。 例如,如果你这样做:

# Set the logger:
logger = Logger.new($stdout)
logger.level = Logger::DEBUG
logger.datetime_format = "%Y-%m-%d %H:%M:%S"

logger.info("This is an info log...")
logger.error("This is an error log...")

您最终会得到以下日志:

I, [2015-01-20 14:02:29#17329]  INFO -- myProg: This is an info log...
E, [2015-01-20 14:02:29#17329] ERROR -- myProg: This is an error log...

如果您想要完全自定义日志,则可以使用logger.formatter。 例如,如果你这样做:

# Set the logger:
logger = Logger.new($stdout)
logger.level = Logger::DEBUG
logger.formatter = proc do |severity, datetime, progname, msg|
    date_format = datetime.strftime("%Y-%m-%d %H:%M:%S")
    if severity == "INFO" or severity == "WARN"
        "[#{date_format}] #{severity}  (#{progname}): #{msg}\n"
    else        
        "[#{date_format}] #{severity} (#{progname}): #{msg}\n"
    end
end

logger.info("This is an info log...")
logger.error("This is an error log...")

您最终会得到以下日志:

[2015-01-20 14:48:04] INFO  (myProg): This is an info log...
[2015-01-20 14:48:04] ERROR (myProg): This is an error log...