logging模块
打印日志的目的
1 操作审计
2 维护排错
3 数据分析
logging模块的日志等级:
1 debug
2 info
3 warning
4 error
5 critical
日志切割与输出
1 直接输出在屏幕
import logging
import time sh = logging.StreamHandler() logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p', handlers=[sh,], level=logging.ERROR ) for i in range(1, 100000): time.sleep(1) logging.error('KeyboardInterrupt error %s' % str(i))
2 根据时间切割
import time import logging from logging import handlers fh = handlers.TimedRotatingFileHandler(filename='x2.log', when='s', interval=5, encoding='utf-8') logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p', handlers=[fh,], level=logging.ERROR ) for i in range(1, 100000): time.sleep(1) logging.error('KeyboardInterrupt error %s' % str(i))
3 根据大小切割
import time import logging from logging import handlers sh = logging.StreamHandler() rh = handlers.RotatingFileHandler('myapp.log', maxBytes=1024, backupCount=5) logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p', handlers=[ rh,], level=logging.ERROR ) for i in range(1, 100000): time.sleep(1) logging.error('KeyboardInterrupt error %s' % str(i))

浙公网安备 33010602011771号