如何格式化 ruby 记录器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14382252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to format ruby logger?
提问by Stein Dekker
How do you format the ruby logger?
你如何格式化 ruby 记录器?
回答by Casper
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.
回答by Paolo Rovelli
If you want to format only the time, you can easily do it with datetime_formatand the standard format specification. For example, if you do:
如果只想格式化时间,可以使用datetime_format和标准格式规范轻松完成。例如,如果你这样做:
# 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...")
You will end up with logs such as:
您最终会得到日志,例如:
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...
If, instead, you want to completely customize your log, you can use logger.formatter. For example, if you do:
相反,如果您想完全自定义您的日志,则可以使用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...")
You will end up with logs such as:
您最终会得到日志,例如:
[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...

