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))

这似乎不起作用,我遇到语法错误,将所有类型的异常记录到文件中的正确方法是什么


当前回答

您可以使用logger.exception(“msg”)记录带有回溯的异常:

try:
    #your code
except Exception as e:
    logger.exception('Failed: ' + str(e))

其他回答

您必须定义要捕获的异常类型。因此,对于一般异常(无论如何都会记录),写Exception,e:而不是Exception。

另一种可能是用这种方式编写整个try/except代码:

try:
    with open(filepath,'rb') as f:
        con.storbinary('STOR '+ filepath, f)
    logger.info('File successfully uploaded to '+ FTPADDR)
except Exception, e: # work on python 2.x
    logger.error('Failed to upload to ftp: '+ str(e))

在Python 3.x和Python 2.x的现代版本中,使用Exception作为e,而不是Exception,e:

try:
    with open(filepath,'rb') as f:
        con.storbinary('STOR '+ filepath, f)
    logger.info('File successfully uploaded to '+ FTPADDR)
except Exception as e: # work on python 3.x
    logger.error('Failed to upload to ftp: '+ str(e))

使用str(ex)打印执行

try:
   #your code
except ex:
   print(str(ex))

将其更新为更简单的日志记录器(适用于python2和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是错误消息。

还有一种方法可以获得传递给异常类的原始值,而不必更改内容类型。

例如,我在我的一个框架中生成带有错误消息的类型代码。

try:
    # TODO: Your exceptional code here 
    raise Exception((1, "Your code wants the program to exit"))

except Exception as e:
    print("Exception Type:", e.args[0][0], "Message:", e.args[0][1])

输出

Exception Type: 1 Message: 'Your code wants the program to exit'

使用str(e)或repr(e)表示异常,您将无法获得实际的堆栈跟踪,因此查找异常的位置没有帮助。

在阅读了其他答案和日志记录包文档后,以下两种方法非常适合打印实际堆栈跟踪,以便于调试:

将logger.debug()与参数exc_info一起使用

try:
    # my code
except SomeError as e:
    logger.debug(e, exc_info=True)

使用logger.exception()

或者我们可以直接使用logger.exception()打印异常。

try:
    # my code
except SomeError as e:
    logger.exception(e)