logging模块

  • 用途:服务器运行日志、运维日志...
import logging
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler # 1.生成logger对象
logger = logging.getLogger('web')
logger.setLevel(logging.DEBUG) # 先设置全局过滤,不然后面的设置debug也是无效的 # 2.生成handler对象
ch = logging.StreamHandler() # 输出到屏幕
fh = logging.FileHandler('web.log') # 输出到文件 fh1 = RotatingFileHandler('web1.log', maxBytes=100, backupCount=3)
fh2 = TimedRotatingFileHandler('web2.log', when='S', interval=5) ch.setLevel(logging.CRITICAL)
fh.setLevel(logging.ERROR) # 可对每个handler设置级别,也可以设置全局:默认warning
fh1.setLevel(logging.DEBUG) # 2.1把handler对象绑定到logger对象
logger.addHandler(ch)
logger.addHandler(fh)
logger.addHandler(fh1)
logger.addHandler(fh2) # 3.生成formatter对象
file_fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file1_fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file2_fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(lineno)s - %(message)s') # 3.1 把formatter绑定到handler对象
ch.setFormatter(console_fmt)
fh.setFormatter(file_fmt)
fh1.setFormatter(file1_fmt)
fh2.setFormatter(file2_fmt) logger.debug('test log1')
logger.info('test_log2')
logger.warning('test_log3')
logger.error('test_log4')
logger.critical('test_log5')
05-18 22:56