python exception message capturing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import ftplib import urllib2 import os import logging logger = logging.getLogger('ftpuploader') hdlr = logging.FileHandler('ftplog.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) FTPADDR ="some ftp address" def upload_to_ftp(con, filepath): try: f = open(filepath,'rb') # file to send con.storbinary('STOR '+ filepath, f) # Send the file f.close() # Close file and FTP logger.info('File successfully uploaded to '+ FTPADDR) except, e: logger.error('Failed to upload to ftp: '+ str(e)) |
这似乎不起作用,我发现语法错误,将所有异常记录到文件中的正确方法是什么?
必须定义要捕捉的异常类型。因此,编写EDCOX1×0×ED,而不是EDCOX1,1,对于一般异常(无论如何都要记录)。
另一种可能是用这种方式编写整个try/except代码:
1 2 3 4 5 6 | try: with open(filepath,'rb') as f: con.storbinary('STOR '+ filepath, f) logger.info('File successfully uploaded to '+ FTPADDR) except Exception, e: logger.error('Failed to upload to ftp: '+ str(e)) |
在python 3.x和python 2.x的现代版本中,使用
1 2 3 4 5 6 | try: with open(filepath,'rb') as f: con.storbinary('STOR '+ filepath, f) logger.info('File successfully uploaded to '+ FTPADDR) except Exception as e: logger.error('Failed to upload to ftp: '+ str(e)) |
Python3不再支持该语法。改为使用以下内容。
1 2 3 4 | try: do_something() except BaseException as e: logger.error('Failed to do something: ' + str(e)) |
将其更新为更简单的日志程序(适用于python 2和3)。您不需要追溯模块。
1 2 3 4 5 6 7 8 9 10 | import logging logger = logging.Logger('catch_all') def catchEverythingInLog(): try: ... do something ... except Exception as e: logger.error(e, exc_info=True) ... exception handling ... |
这是旧方法(尽管仍然有效):
1 2 3 4 5 6 7 8 | import sys, traceback def catchEverything(): try: ... some operation(s) ... except: exc_type, exc_value, exc_traceback = sys.exc_info() ... exception handling ... |
exc_值是错误消息。
在某些情况下,您可以使用e.message或e.messages。但并非所有情况下都适用。无论如何,使用str(e)更安全。
1 2 3 4 | try: ... except Exception as e: print(e.message) |
您可以使用
1 2 3 4 | try: #your code except Exception as e: logger.exception('Failed: ' + str(e)) |
在python 3.6之后,可以使用格式化字符串文字。很整洁!(https://docs.python.org/3/whatsnew/3.6.html whatsnew36-pep498)
1 2 3 4 | try ... except Exception as e: logger.error(f"Failed to upload to ftp: {e}") |
如果您需要错误类、错误消息和堆栈跟踪(或两者之一),请使用
使用一些格式的最小工作代码,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import sys import traceback try: ans = 1/0 except BaseException as ex: # Get current system exception ex_type, ex_value, ex_traceback = sys.exc_info() # Extract unformatter stack traces as tuples trace_back = traceback.extract_tb(ex_traceback) # Format stacktrace stack_trace = list() for trace in trace_back: stack_trace.append("File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3])) print("Exception type : %s" % ex_type.__name__) print("Exception message : %s" %ex_value) print("Stack trace : %s" %stack_trace) |
输出如下:
1 2 3 | Exception type : ZeroDivisionError Exception message : division by zero Stack trace : ['File : .\\test.py , Line : 5, Func.Name : <module>, Message : ans = 1/0'] |
sys·Excel()
这将为您提供有关最近异常的异常详细信息。它返回一个元组。下面是etple值
回溯是回溯对象的一个实例。您可以使用提供的方法格式化跟踪。更多信息可从回溯文档中找到。
可以显式指定基类异常类型。然而,这只会捕获BaseExchange的衍生品。虽然这包括所有实现提供的异常,但也有可能引发任意的旧样式类。
1 2 3 4 | try: do_something() except BaseException, e: logger.error('Failed to do something: ' + str(e)) |
使用str(ex)打印execption
1 2 3 4 | try: #your code except ex: print(str(ex)) |