Python中的traceback模块被用于跟踪异常返回信息,可以在logging中记录下traceback:
import logging logger = logging.getLogger(__name__) logger.setLevel(level = logging.INFO) handler = logging.FileHandler("log.txt") handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) console = logging.StreamHandler() console.setLevel(logging.INFO) logger.addHandler(handler) logger.addHandler(console) logger.info("Start print log") logger.debug("Do something") logger.warning("Something maybe fail.") try: open("sklearn.txt", "rb") except (SystemExit, KeyboardInterrupt): raise except Exception: logger.error("Faild to open sklearn.txt from logger.error", exc_info = True) logger.info("Finish") #在这里也可以将日志捕获异常编写成一个通用类,然后尽量分各种类型的traceback去编写捕获方法
也可以使用 logger.exception(msg, _args),它等价于 logger.error(msg, exc_info=True, _args)
将
logger.error("Faild to open sklearn.txt from logger.error", exc_info=True)
修改为:
logger.exception("Failed to open sklearn.txt from logger.exception")
控制台 和 日志文件log.txt中输出:
Start print log Something maybe fail. Failed to open sklearn.txt from logger.exception Traceback (most recent call last): File "G:\zhb7627\Code\Eclipse WorkSpace\PythonTest\test.py", line 23, in <module> open("sklearn.txt","rb") IOError: [Errno 2] No such file or directory: 'sklearn.txt' Finish
后面把堆栈信息也 放出来了,方便跟踪业务代码的调用方法链,(部分)参考代码如下:
def execute(self, sql): """ 插入、修改、删除 等执行操作 :param sql: SQL字符串 :return: 成功则返回新插入数据的主键ID 或 受影响的行数,失败返回False """ if self.__auto_commit is False: return self.__execute(sql) else: try: ret = self.__execute(sql) self.__conn.commit() return ret except pymysql.Error as e: self.__conn.rollback() err_msg = string_str(e) + "\n" + sql logger.exception(err_msg, stack_info=True) # 【注意】把stack堆栈信息也打印出来 return False
异常时输出:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2020-10-08 10:23:26,774 [ERROR] mysql.py:130 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ (1146, "Table 'jianbao_blog.bookmarks' doesn't exist") UPDATE bookmarks SET stock_name='\'顺丰股份\'' WHERE stock_no='300002' Traceback (most recent call last): File "D:\python\PyCharmProjects\wenjianbao\jianbao_blog\framework\utils\database\mysql.py", line 124, in execute ret = self.__execute(sql) File "D:\python\PyCharmProjects\wenjianbao\jianbao_blog\framework\utils\database\mysql.py", line 102, in __execute cursor.execute(sql) File "D:\python\Anaconda3\lib\site-packages\pymysql\cursors.py", line 163, in execute result = self._query(query) File "D:\python\Anaconda3\lib\site-packages\pymysql\cursors.py", line 321, in _query conn.query(q) File "D:\python\Anaconda3\lib\site-packages\pymysql\connections.py", line 505, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "D:\python\Anaconda3\lib\site-packages\pymysql\connections.py", line 724, in _read_query_result result.read() File "D:\python\Anaconda3\lib\site-packages\pymysql\connections.py", line 1069, in read first_packet = self.connection._read_packet() File "D:\python\Anaconda3\lib\site-packages\pymysql\connections.py", line 676, in _read_packet packet.raise_for_error() File "D:\python\Anaconda3\lib\site-packages\pymysql\protocol.py", line 223, in raise_for_error err.raise_mysql_exception(self._data) File "D:\python\Anaconda3\lib\site-packages\pymysql\err.py", line 107, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.ProgrammingError: (1146, "Table 'jianbao_blog.bookmarks' doesn't exist") Stack (most recent call last): File "D:/python/PyCharmProjects/wenjianbao/jianbao_blog/_tests/database/mysql_update.py", line 6, in <module> res = db.update("bookmarks", { File "D:\python\PyCharmProjects\wenjianbao\jianbao_blog\framework\utils\database\mysql.py", line 175, in update return self.execute(sql) File "D:\python\PyCharmProjects\wenjianbao\jianbao_blog\framework\utils\database\mysql.py", line 130, in execute logger.exception(err_msg, stack_info=True) Process finished with exit code 0