python 日志模块
日志作用
- 调试
- 辅助定位问题
- 数据分析
日志的级别
日志的用法
设置日志的级别
logging.basicConfig(level=logging.INFO)
保存日志到文件
logging.basicConfig(filename=‘myapp.log’, level=logging.INFO)
设置时间格式
logging.basicConfig(filename=‘myapp.log’, level=logging.INFO,format=‘%(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)’, datefmt=‘%m/%d/%Y %I:%M:%S %p’)
python 日志进阶
python 日志记录流程
python 日志定义
import logging
import os
# create logger 创建一个logger 记录器
logger = logging.getLogger(os.path.basename(__file__))
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')