python3 logging模块
import logging """单一日志的简单配置,写入日志的编码目前默认是gbk""" logging.basicConfig( filename='xx.log', # 日志文件 format='%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', # 日志时间格式 level=30) # 日志等级.30分以上的信息会记录到日志 # 5个等级. logging.critical("严重信息") # 50分 logging.error("错误信息") # 40分 logging.warning("警告信息") # 30分 logging.info("普通信息") # 20分 logging.debug("详细信息") # 10分 logging.log(35, "自定义消息") # 35分
import logging """多个日志文件的配置""" file_handler = logging.FileHandler('user.log', 'a', encoding='utf-8') file_handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s')) logger1 = logging.Logger('用户信息', level=logging.ERROR) logger1.addHandler(file_handler) # 把logger和handler绑定在一起 file_handler2 = logging.FileHandler('sys.log', 'a', encoding='utf-8') file_handler2.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s")) logger2 = logging.Logger('系统信息', level=logging.ERROR) logger2.addHandler(file_handler2) logger1.error('用户信息') logger2.error('系统信息')
try: print(1/0) # ZeroDivisionError: division by zero lst = [1, 2, 3] it = lst.__iter__() print(it.__next__()) print(it.__next__()) print(it.__next__()) print(it.__next__()) except StopIteration: print("迭代器没数据了") except ZeroDivisionError: print("除数不能为零") except Exception: print("程序出错了") finally: print("有没有错误都走这里")
import logging import traceback """多个日志文件的配置""" file_handler = logging.FileHandler('user.log', 'a', encoding='utf-8') file_handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s')) logger1 = logging.Logger('用户信息', level=logging.ERROR) logger1.addHandler(file_handler) # 把logger和handler绑定在一起 file_handler2 = logging.FileHandler('sys.log', 'a', encoding='utf-8') file_handler2.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s")) logger2 = logging.Logger('系统信息', level=logging.ERROR) logger2.addHandler(file_handler2) try: print(1/0) except Exception: logger1.error(traceback.format_exc()) # format_exc() 拿到错误位置 finally: print("报不报错,都会走这里!")