赞
踩
一、项目中仅有一个日志文件
当项目中仅有一个日志文件时,可以使用logging.basicConfig
import logging
logging.basicConfig(filename='log.log',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=10)
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log')
二、当有多个日志文件时可以使用FileHandler,对于上述记录日志的功能,只能将日志记录在单文件中,如果想要设置多个日志文件,logging.basicConfig将无法完成,需要自定义文件和日志操作对象。
import logging # 定义文件 file1 = logging.FileHandler(filename='l1.log', mode='a', encoding='utf-8') fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s", datefmt='%Y-%m-%d %H:%M:%S') file1.setFormatter(fmt) file2 = logging.FileHandler(filename='l2.log', mode='a', encoding='utf-8') fmt = logging.Formatter() file2.setFormatter(fmt) # 定义日志 logger1 = logging.Logger(name='这里是name', level=logging.ERROR) logger1.addHandler(file1) logger1.addHandler(file2) # logger1.removeHandler(file1) # logger1.removeHandler(file2) # 写日志 logger1.error(msg='这里是msg111') logger1.log(msg='这里是msg222', level=50) # 定义文件 file3 = logging.FileHandler(filename='l3.log', mode='a', encoding='utf-8') fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s", datefmt='%Y-%m-%d %H:%M:%S') file3.setFormatter(fmt) # 定义日志 logger2 = logging.Logger(name='这里是name222222', level=logging.INFO) logger2.addHandler(file3) # 写日志 logger2.info('这里是msg333333')
注:文章copy自出处
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。