Ruby中打印日志:Logger的使用
1.引入'logger'
require 'logger'
2.日志輸出到控制台還是文件
logger = Logger.new(STDOUT) #輸出到控制台
logger = Logger.new("log.txt") #輸出到文件,文件名log.txt
logger = Logger.new(STDERR) #輸出到屏幕
指定寫入文件方式:
file = File.open('foo.log', File::WRONLY | File::APPEND)
# To create new (and to remove old) logfile, add File::CREAT like;
# file = open('foo.log', File::WRONLY | File::APPEND | File::CREAT)
logger = Logger.new(file)
3.日志生成周期
logger = Logger.new('log.log', 'daily') #按天生成
logger = Logger.new('log.log', 'weekly') #按周生成
logger = Logger.new('log.log', 'monthly')#按月生成
4.指定日志大小及保留日志個數
logger = Logger.new('foo.log', 10, 1024000) #保留10個日志文件,每個文件大小1024000字節
5.輸出不同級別的日志
logger.level = Logger::INFO
logger.error("some desption")
logger.fatal("an object #{obj}")
logger.info("that's another instance obj #{obj}")
logger.add(Logger::FATAL) { 'Fatal error!' }
日志級別從大到小分別是:fatal、error、warn、info、debug
6.日志輸出格式及時間格式 默認日志格式: SeverityID, [Date Time mSec #pid] SeverityLabel -- ProgName: message 修改時間格式: logger.datetime_format = "%Y-%m-%d %H:%M:%S"
# e.g. "2004-01-03 00:54:26" 修改日志格式: logger.formatter = proc { |severity, datetime, progname, msg|
"#{datetime}: #{msg}\n"
}
# e.g. "Thu Sep 22 08:51:08 GMT+9:00 2005: hello world"
重要文章閱讀:Ruby入門--Linux/Windows下的安裝、代碼開發及Rails實戰 http://www.linuxidc.com/Linux/2014-04/100242.htm
Ruby on rails初體驗系列文章:
http://www.linuxidc.com/Linux/2014-04/100245.htm
http://www.linuxidc.com/Linux/2014-04/100246.htm
http://www.linuxidc.com/Linux/2014-04/100247.htm