import logging #定义日志 logger = logging.basicConfig(filename='xxxxxxx.txt', format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=30) #这种方法生成日志不好定位错误位置
#定义日志
logger = logging.basicConfig(filename='xxxxxxx.txt',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=30)
#这种方法生成日志不好定位错误位置
# logging.debug('x1') # 10
# logging.info('x2') # 20
# logging.warning('x3') # 30
# logging.error('x4') # 40
# logging.critical('x5') # 50
# logging.log(10,'x6')
#推荐使用这种
import traceback
def func():
try:
a = a +1
except Exception as e:
# 获取当前错误的堆栈信息
msg = traceback.format_exc()
logging.error(msg)
func()
当要生成两个日志文件的时候,可自定义日志
import logging# 创建一个操作日志的对象logger(依赖FileHandler)
file_handler = logging.FileHandler('l1.log', 'a', encoding='utf-8')
file_handler.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s"))
logger1 = logging.Logger('s1', level=logging.ERROR)
logger1.addHandler(file_handler)
logger1.error('123123123')
# 在创建一个操作日志的对象logger(依赖FileHandler)
file_handler2 = logging.FileHandler('l2.log', 'a', encoding='utf-8')
file_handler2.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s"))
logger2 = logging.Logger('s2', level=logging.ERROR)
logger2.addHandler(file_handler2)
logger2.error('666')