python logging 模块
logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;
1. 控制台基本使用:
import logging
logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) logger.info("Start print log") logger.debug("Do something") logger.warning("Something maybe fail.") logger.info("Finish")
2. 将日志输出到文件
import logging
# logger 绑定 handler(可以多个), handler 绑定formatter logger = logging.getLogger(__name__) #将当前文件名作为日志名生成logger 对象 logger.setLevel(level = logging.INFO) # 为logger设置默认等级,低于此等级的信息均被忽略 Debug<Info<Warning<ERROR<critical<fatal handler = logging.FileHandler("log.txt") #生成 fileHandler(用的最多的就是 streamhandler 和filehandler) handler.setLevel(logging.INFO) #为handler 设置等级 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') #设置日志格式 handler.setFormatter(formatter) handler 绑定格式 console = logging.StreamHandler() console.setLevel(logging.INFO) logger.addHandler(handler) logger.addHandler(console) logger.info("Start print log") logger.debug("Do something") logger.warning("Something maybe fail.") logger.info("Finish")
3 旋转型日志
生成给定数量日志,不带数字的是最新生成,可以设置每个日志的大小
import logging from logging.handlers import RotatingFileHandler
logger = logging.getLogger(__name__) logger.setLevel(level = logging.INFO)
#定义一个RotatingFileHandler,最多备份3个日志文件,每个日志文件最大1K rHandler = RotatingFileHandler("log.txt",maxBytes = 1*1024,backupCount = 3) rHandler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') rHandler.setFormatter(formatter) console = logging.StreamHandler() console.setLevel(logging.INFO) console.setFormatter(formatter) logger.addHandler(rHandler) logger.addHandler(console) logger.info("Start print log") logger.debug("Do something") logger.warning("Something maybe fail.") logger.info("Finish")