记录Python异常的最佳方式 [英] Best way to log a Python exception

查看:133
本文介绍了记录Python异常的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  try:
#coode在这里
除了异常,e:
logging.error(e)

要打印有关异常的更多信息和生成它的代码,而不仅仅是异常字符串?像线条或堆栈跟踪这样的事情会很好。

解决方案

logger.exception 这样做。



例如:

  import logging 
try:
1/0
除了例外为e:
logging.exception(message)

输出:

 错误:root:message 
追溯(最近最近呼叫最后):
文件< stdin>,第2行,< module>
ZeroDivisionError:整数除数或模数为零

@Paulo Check 注意到,请注意,在Python 3中,您必须调用 logging.exception 方法只是在内部,除了部分,如果你在任意的地方调用这个方法,你可能会得到一个奇怪的例外,文档警告这个。


I'm printing my exceptions to a log file currently with:

try:
    # coode in here
except Exception, e:
    logging.error(e)

Could I be printing more information about the exception and the code that generated it than just the exception string? Things like line numbers or stack traces would be great.

解决方案

logger.exception does that.

For example:

import logging
try:
    1/0
except Exception as e:
    logging.exception("message")

Output:

ERROR:root:message
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

@Paulo Cheque notes, "be aware that in Python 3 you must call the logging.exception method just inside the except part. If you call this method in an arbitrary place you may get a bizarre exception. The docs alert about that."

这篇关于记录Python异常的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆