2012-02-14 59 views
0

我添加记录到与异常交易一些Python代码,在下面什么为希望记录异常细节的正确语法的例子(例如,通过logger.exception())当一个类型错误或AttributeError的发生?Python异常日志记录,正确的语法?

try: 
     ... 
    except (TypeError, AttributeError): 
     # want to do a logger.exception(x) here but not sure what to use for x 
     ... 
     raise CustomError("Unable to parse column status) 
+2

你试过了吗? – 2012-02-14 14:51:46

回答

0

如果你想要异常的详细信息,你需要异常本身绑定到一个局部变量,就像这样:

except (TypeError, AttributeError), e: 
    # e is the Exception object 
    logger.exception(e) 

如果您需要根据异常的类型做不同的事情,那么你可以单独赶上他们:

except TypeError, e: 
    logger.exception('There was a Type Error; details are %s' % e) 
    # Do something, or raise another exception 
except AttributeError, e: 
    logger.exception('There was an Attribute Error; details are %s' % e) 
    # Do something, or raise another exception 

如果您需要有关异常本身的上下文的详细信息,窥视sys.exc_info()功能;它可以为您提供回溯,以及有关发生异常的详细信息。

+0

'例外(...)',或更确切地说,'exc_info = TRUE'参数,包括从'sys.exc_info异常信息()',使得记录器的实施可以使用它。那么为什么要手动格式化? – AndiDog 2012-02-14 15:14:39

+0

这意味着更多的一般异常处理逻辑,以防万一有用的信息可以完成。不,如果你要做的只是格式化日志信息,没有理由将其从exc_info中提取出来。 – 2012-02-14 15:40:01

+0

我的意思是'“消息%s”%e'应该*不*可以与'logging.exception'呼叫使用,因为异常的信息被自动地存储,并且为了记录的堆栈跟踪所使用的配置的记录器实现中,例如。无需自己格式化。 – AndiDog 2012-02-14 15:51:39

1

exception(...)仅仅是一个方便的方法,该方法只需像其他方法的消息:

def exception(self, msg, *args): 
    """ 
    Convenience method for logging an ERROR with exception information. 
    """ 
    self.error(msg, exc_info=1, *args) 

所以你只需使用它像

logger.exception("Some error message") 

和日志处理程序将自动添加当前异常的异常信息。只能在异常处理程序中使用它(即在except:块中)!

+0

好吧,我会试试看,我不知道信息。对当前异常(如果有多个可能捕获的)将被记录。 – 2012-02-14 14:56:45