日志
1、为什么有日志?
给开发人员错误,用于排查错误。
2、只能往一个文件中写:
import traceback #获取当前错误的堆栈信息
import logging
import traceback # 把错误的堆栈写到日志
logger = logging.basicConfig(filename='xxx.txt',
format='%(asctime)s - %(name)s - %(module)s: %(message)s',
datefmt='%Y-%m-%d %H-%M-%S',
level=30)
logging.debug('x1')
logging.info('x2')
logging.warning('x3')
logging.error('x4')
logging.critical('x5')
def func():
try:
a = a + 1
except Exception as e:
msg = traceback.format_exc()
logging.error(msg)
func()
3、往多个文件写的方法:
import logging
# 定义文件
file_1_1 = logging.FileHandler('l1_1.log', 'a', encoding='utf-8')
fmt1 = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s")
file_1_1.setFormatter(fmt1)
file_1_2 = logging.FileHandler('l1_2.log', 'a', encoding='utf-8')
fmt2 = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s")
file_1_2.setFormatter(fmt2)
# 定义日志
logger1 = logging.Logger('s1', level=logging.ERROR)
logger1.addHandler(file_1_1)
logger2 = logging.Logger('s2', level=logging.ERROR)
logger2.addHandler(file_1_2)
# 写日志
logger1.critical('1111')
logger2.critical('2222')