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))
这彷佛不起做用,出现语法错误,将全部类型的异常记录到文件中的正确方法是什么 python
python 3再也不支持该语法。请改用如下内容。 安全
try: do_something() except BaseException as e: logger.error('Failed to do something: ' + str(e))
将其更新为更简单的记录器(适用于python 2和3)。 您不须要回溯模块。 url
import logging logger = logging.Logger('catch_all') def catchEverythingInLog(): try: ... do something ... except Exception as e: logger.error(e, exc_info=True) ... exception handling ...
如今这是旧方法(尽管仍然有效): spa
import sys, traceback def catchEverything(): try: ... some operation(s) ... except: exc_type, exc_value, exc_traceback = sys.exc_info() ... exception handling ...
exc_value是错误消息。 code
您能够使用logger.exception("msg")
来记录带有回溯的异常: orm
try: #your code except Exception as e: logger.exception('Failed: ' + str(e))
在某些状况下,您能够使用e.message或e.messages ..可是,并不是在全部状况下都有效。 不管如何,使用str(e)更安全 get
try: ... except Exception as e: print(e.message)
您能够尝试明确指定BaseException类型。 可是,这只会捕获BaseException的派生类。 尽管这包括全部实现提供的异常,但也有可能引起任意旧式类。 io
try: do_something() except BaseException, e: logger.error('Failed to do something: ' + str(e))