python异常消息捕获

python异常消息捕获,python,exception,logging,except,Python,Exception,Logging,Except,这似乎不起作用,我得到了语法错误,记录文件中所有类型异常的正确方法是什么您可以尝试显式指定BaseException类型。然而,这将只捕获BaseException的派生。虽然这包括所有实现提供的异常,但也可能引发任意的旧式类 import ftplib import urllib2 import os import logging logger = logging.getLogger('ftpuploader') hdlr = logging.FileHandler('ftplog.log')

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

您可以尝试显式指定BaseException类型。然而,这将只捕获BaseException的派生。虽然这包括所有实现提供的异常,但也可能引发任意的旧式类

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

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

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

try:
  do_something()
except BaseException, e:
  logger.error('Failed to do something: ' + str(e))
在Python3.x和Python2.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, e: # work on python 2.x
    logger.error('Failed to upload to ftp: '+ str(e))

python 3不再支持该语法。改用以下方法

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

将此更新为更简单的logger(适用于Python2和Python3)。您不需要回溯模块

try:
    do_something()
except BaseException as e:
    logger.error('Failed to do something: ' + str(e))
这是现在的老方法(尽管仍然有效):


exc_值是错误消息。

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

import sys, traceback

def catchEverything():
    try:
        ... some operation(s) ...
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        ... exception handling ...

在某些情况下,您可以使用e.messagee.messages。。但它并非在所有情况下都有效。无论如何,使用str(e)

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

如果需要错误类、错误消息和堆栈跟踪,请使用sys.exc_info()

具有某些格式的最小工作代码:

try:
  ...
except Exception as e:
  print(e.message)
这将提供以下输出:

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)
异常类型:ZeroDivisionError
异常消息:被零除
堆栈跟踪:['文件:.\\test.py,行:5,函数名:,消息:ans=1/0']
函数提供有关最近异常的详细信息。它返回一个元组
(类型、值、回溯)

回溯
是回溯对象的一个实例。您可以使用提供的方法格式化跟踪。更多信息请参见。

使用str(ex)打印执行选项

Exception type : ZeroDivisionError
Exception message : division by zero
Stack trace : ['File : .\\test.py , Line : 5, Func.Name : <module>, Message : ans = 1/0']

在Python3.6之后,可以使用格式化的字符串文字。它很整洁!()


对于未来的奋斗者, 在Python3.8.2(以及之前的一些版本)中,语法是

try
 ...
except Exception as e:
    logger.error(f"Failed to upload to ftp: {e}")
使用
str(e)
repr(e)
来表示异常,将无法获得实际的堆栈跟踪,因此查找异常的位置没有帮助

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

使用参数
exc\u info
试试看:
#我的代码
除了一些错误,例如:
logger.debug(e,exc_info=True)
使用
logger.exception()
或者我们可以直接使用
logger.exception()
打印异常

试试看:
#我的代码
除了一些错误,例如:
记录器.异常(e)


您的缩进已损坏。并且在
之后省略
除了
@SvenMarnach,如果在
之后省略
除了
,您将得到
全局名称“e”没有定义
,这比错误的语法好不了多少。@Val:应该是
除了异常作为e
除了异常,e
,取决于Python版本。可能在这8个答案附近,但当您打开一个文件时,关闭部分不应该在try语句中,而应该在finally语句中,或者由with语句包装。您可以像在requests包中的UnitTests那样执行。实际上,您应该使用logger.error('Failed to do something:%s',str(e))这样,如果记录器级别高于错误,则不会执行字符串插值。@avyfain-您是不正确的。语句
logging.error('foo%s',str(e))
将始终将
e
转换为字符串。为了实现您的目标,您将使用
logging.error('foo%s',e)
-从而允许日志框架执行(或不执行)转换。作为日志异常的替代方法,您可以使用
logger.exception(e)
。它将在相同的
日志记录级别上使用回溯记录异常。错误
我想他/她指的是“异常除外,e:”注意
异常
异常除外
不在同一级别上
Exception
在Python3中可以工作,但它不会捕获
键盘中断
(如果您希望能够中断代码,这可能非常方便!),而
BaseException
会捕获任何异常。有关异常的层次结构,请参见。巧合的是,
e.msg
Exception
类的字符串表示形式。或者简单地说,
logger.Exception(e)
。这是我首选的方法。我想打印字符串对于日志记录很有用,但是如果我需要使用这些信息做任何事情,我需要的不仅仅是一个字符串。在第二个示例中,您不需要“导入回溯”,对吗?repr(e)为您提供了异常(和消息字符串);str(e)只给出消息字符串。作为记录异常的替代方法,您可以使用
logger.exception(e)
。它将在相同的
日志记录级别上使用回溯记录异常。错误
级别。@mbdevpl这似乎不是真的。它似乎对异常调用str():
异常除外,e:
在python 3中向我抛出一个语法错误。这是预期的吗?@CharlieParker在Python3中写
异常除外为e:
问题是,例如,如果你
异常除外为e
,并且
e
是一个
IOError
,你会得到
e.errno
e.filename
,和
e.strerror
,但显然没有
e.message(至少在Python 2.7.12中是这样)。如果要捕获错误消息,请使用
str(e)
,与其他答案一样。@epalm如果捕获IOB错误该怎么办
try:
   #your code
except ex:
   print(str(ex))
try
 ...
except Exception as e:
    logger.error(f"Failed to upload to ftp: {e}")
except Attribute as e:
    print(e)