1.logger创建
# 输出到标准输出logger = Logger.new(STDERR)logger = Logger.new(STDOUT)# 输出到指定文件logger = Logger.new('logfile.log')# 输出到指定打开/创建模式的文件file = File.open('foo.log', File::WRONLY | File::APPEND | File::CREAT)# To create new (and to remove old) logfile, add File::CREAT like:# file = File.open('foo.log', File::WRONLY | File::APPEND | File::CREAT)logger = Logger.new(file)# 指定日志大小及保留日志个数logger = Logger.new('foo.log', 10, 1024000)
# 日志生成周期 logger = Logger.new('foo.log', 'daily') logger = Logger.new('foo.log', 'weekly') logger = Logger.new('foo.log', 'monthly')
2.设置日志级别
logger.level = Logger::DEBUGlogger.level = Logger::INFOlogger.level = Logger::WARNlogger.level = Logger::FATALlogger.level = Logger::UNKNOWN
3.设置日志输出格式
# datetime_format=时间格式化logger.datetime_format = '%Y-%m-%d %H:%M:%S'# formatter=方法改变整体格式logger.formatter = proc do |severity, datetime, progname, msg| "#{datetime}: #{msg}\n"end
4.日志打印
logger.info("User-input: #{input.dump}")logger.info("User-input: %p" % input)logger.info "Waiting for input from user"logger.info { "User typed #{input}" }