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))
这似乎不起作用,我得到语法错误,这是什么正确的方法来记录文件的所有类型的异常
9 回答
在某些情况下,您可以使用 e.message 或 e.messages ..但它并不适用于所有情况 . 无论如何更安全的是使用 str(e)
您可以使用
logger.exception("msg")
通过回溯来记录异常:您可以尝试显式指定BaseException类型 . 但是,这只会捕获BaseException的衍生物 . 虽然这包括所有实现提供的异常,但也可能引发任意旧式类 .
您必须定义要捕获的异常类型 . 所以写
except Exception, e:
而不是except, e:
作为一般例外(无论如何都要记录) .其他可能性是以这种方式编写整个try / except代码:
在Python 3.x和现代版本的Python 2.x中使用
except Exception as e
而不是except Exception, e
:python 3中不再支持该语法 . 请改用以下内容 .
将此更新为更简单的 Logger (适用于python 2和3) . 您不需要回溯模块 .
这是现在的方式(尽管仍然有效):
exc_value是错误消息 .
如果需要错误类,错误消息和堆栈跟踪(或其中任何一个),请使用 sys.exec_info() .
具有一些格式的最小工作代码,
这将给出以下输出,
sys.exec_info()
这将为您提供有关最新异常的异常详细信息 . 它返回一个元组 . 以下是元组值
(type, value, traceback)
.traceback是traceback对象的一个实例 . 您可以使用提供的方法格式化跟踪 . 更多信息可以在traceback documentation找到
在python 3.6之后,您可以使用格式化的字符串文字 . 它很整洁! (https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498)
使用str(ex)打印execption