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"