pythonexception消息捕获
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))
这似乎没有工作,我得到语法错误,这是做这种logging文件的所有types的exception的正确方法
你必须定义你想要捕获哪种types的exception。 因此, except Exception, e:
except, e:
一般的exception(反正会被logging)。
其他的可能性是这样写你的整个尝试/除了代码:
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中不再支持该语法。请改为使用下面的代码。
try: do_something() except BaseException as e: logger.error('Failed to do something: ' + str(e))
更新这个更简单的logging器(适用于Python 2和3)。 你不需要回溯模块。
import logging logger = logging.Logger('catch_all') def catchEverythingInLog(): try: ... do something ... except Exception as e: logger.error(e, exc_info=True) ... exception handling ...
这现在是旧的方式(虽然仍然有效):
import sys, traceback def catchEverything(): try: ... some operation(s) ... except: exc_type, exc_value, exc_traceback = sys.exc_info() ... exception handling ...
exc_value是错误信息。
您可以使用logger.exception("msg")
来logging具有回溯的exception:
try: #your code except Exception as e: logger.exception('Failed: ' + str(e))
您可以使用e.message或e.messages …
try: ... except Exception as e: print(e.message)
您可以尝试显式指定BaseExceptiontypes。 但是,这只会捕获BaseException的派生。 虽然这包括所有实现提供的exception,但也可能引发任意旧式类。
try: do_something() except BaseException, e: logger.error('Failed to do something: ' + str(e))