将日志同时输出到文件和屏幕
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") # 指定输出的格式和内容
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
handler.setFormatter(formatter)
-----------------------------------------------------
console = logging.StreamHandler()
console.setLevel(logging.INFO) # 将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象
console.setFormatter(formatter)
--------------------------------------------------
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(console)
logger.addHandler(handler )
logging之日志回滚:
Rthandler = RotatingFileHandler('myapp.log', maxBytes=10*1024*1024, backupCount=5) # 最多备份5个日志文件,每个日志文件最大10M from logging.handlers import RotatingFileHandler
Rthandler.setLevel(logging.INFO)
Rthandler.setFormatter(formatter)
---------------------------------------------------------------
TRthandler = logging.handlers.TimedRotatingFileHandler(filename=‘myCrawler.log’, when='D', interval=1, backupCount=5) # 每隔1天备份日志文件,最多备份5个日志文件
TRthandler .setLevel(logging.INFO)
TRthandler .setFormatter(formatter)
由于StreamHandler和FileHandler是常用的日志处理方式,所以直接包含在logging模块中,而其他方式则包含在logging.handlers模块中
logging.handlers.BaseRotatingHandler
logging.handlers.RotatingFileHandler
logging.handlers.TimedRotatingFileHandler
logging.handlers.SocketHandler: 远程输出日志到TCP/IP sockets
logging.handlers.DatagramHandler: 远程输出日志到UDP sockets
logging.handlers.SMTPHandler: 远程输出日志到邮件地址
logging.handlers.SysLogHandler: 日志输出到syslog
logging.handlers.NTEventLogHandler: 远程输出日志到Windows NT/2000/XP的事件日志
logging.handlers.MemoryHandler: 日志输出到内存中的制定buffer
logging.handlers.HTTPHandler: 通过"GET"或"POST"远程输出到HTTP服务器