先看代码:
gem install logger
require 'logger'
file = File.open('F:\log.log', File::WRONLY | File::APPEND)
# $logger = Logger.new(STDOUT) #输出到控制台
$logger = Logger.new(file) #输出文件
$logger.level = Logger::WARN #设定高于这个级别的才会输出
#修改log的输出格式
$logger.formatter = proc { |severity, datetime, progname, msg|
"#{severity}: #{datetime}: #{msg}\n"
}
#输出内容
$logger.debug "da#{9+9}fsdfas"
$logger.warn ""
$logger.error ""
$logger.info [1,2,34,5,6,9]
$logger.fatal "fatal"
$logger.fatal "==========================="
p $logger
Ruby中打印日志:Logger的使用
- 引入'logger':
require 'logger'
- 日志输出到控制台还是文件
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)
- 日志生成周期
logger = Logger.new('log.log', 'daily') #按天生成
logger = Logger.new('log.log', 'weekly') #按周生成
logger = Logger.new('log.log', 'monthly')#按月生成
- 指定日志大小及保留日志个数
logger = Logger.new('foo.log', 10, 1024000) #保留10个日志文件,每个文件大小1024000字节
- 输出不同级别的日志
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
- 日志输出格式及时间格式 默认日志格式:
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"