先看代碼:
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 #設(shè)定高于這個(gè)級別的才會(huì)輸出
#修改log的輸出格式
$logger.formatter = proc { |severity, datetime, progname, msg|
"#{severity}: #{datetime}: #{msg}\n"
}
#輸出內(nèi)容
$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')#按月生成
- 指定日志大小及保留日志個(gè)數(shù)
logger = Logger.new('foo.log', 10, 1024000) #保留10個(gè)日志文件蠢熄,每個(gè)文件大小1024000字節(jié)
- 輸出不同級別的日志
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
- 日志輸出格式及時(shí)間格式 默認(rèn)日志格式:
SeverityID, [Date Time mSec #pid] SeverityLabel -- ProgName: message
修改時(shí)間格式: 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"