记录日志:
import logging
logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', # 日志打印格式
level=logging.DEBUG, # 打印级别
filename='new.log', # 打印写入的文件
filemode='w',) # 写入日志的方法,a为追加,w为写入
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critial')
如果是需要一边写入文件,一边打印出来,使用:
logger = logging.getLogger() # 不加名称设置root logger
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s: - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
fh = logging.FileHandler('autostore.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
# 使用StreamHandler输出到屏幕
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
# 添加两个Handler
logger.addHandler(ch)
logger.addHandler(fh)
如果需要记录毫秒级的日志,可以改为:
format='%(asctime)s.%(msecs)03d - %(name)s - %(levelname)s: - %(message)s'
参考文章
python logging模块:https://www.cnblogs.com/dahu-daqing/p/7040764.html