logging日志过滤和日志文件自动截取
1.日志过滤
import logging class IgnoreFilter(logging.Filter): def filter(self,record): return "girl" not in record.getMessage() #如果girl不在record里,则返回True # 1.生成logger对象 logger = logging.getLogger("130") logger.setLevel(logging.DEBUG) #不设置级别,默认最低级别是warning。 logger.addFilter(IgnoreFilter()) # 2.生成handler对象 # 把handler对象绑定到logger ch = logging.StreamHandler() # ch.setLevel(logging.DEBUG) #对屏幕和文件分别设置级别 fh = logging.FileHandler("130.log") # fh.setLevel(logging.ERROR) logger.addHandler(ch) logger.addHandler(fh) # 3.生成formatter对象 # 把formatter对象绑定到handler file_formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s") console_formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(lineno)s %(message)s") ch.setFormatter(console_formatter) fh.setFormatter(file_formatter) logger.debug("miss eat") logger.warning("hello girl")
2.日志截断
2.1 根据日志大小截断
maxBytes 最大字节 backupCount 文件最多存在的个数。
from loggign import handlers
fh = handlers.RotatingFileHandler("130.log",maxBytes=10,backupCount = 5)
2.2 按照时间间隔来截断日志,最多生成五个
when 时间单位,interval 时间间隔。
fh = handlers.TimedRotatingFileHandler("130.log",when = "s",interval = 5,backupCount = 5)
越是困难的事越要立即去做,这样收益才会最大!!!