简体   繁体   English

如何使用python日志框架使用回溯在警告或信息级别记录异常?

[英]How do I log an exception at warning- or info-level with traceback using the python logging framework?

Using something like this: 使用这样的东西:

try:
   # Something...
except Exception as excep:
   logger = logging.getLogger("component")
   logger.warning("something raised an exception: " + excep)
   logger.info("something raised an exception: " + excep)

I would rather not have it on the error-level cause in my special case it is not an error. 我宁愿没有错误级别的原因在我的特殊情况下它不是一个错误。

From the logging documentation : 日志记录文档

There are three keyword arguments in kwargs which are inspected: exc_info , stack_info , and extra . kwargs有三个关键字参数被检查: exc_infostack_infoextra

If exc_info does not evaluate as false, it causes exception information to be added to the logging message. 如果exc_info未评估为false,则会将异常信息添加到日志消息中。 If an exception tuple (in the format returned by sys.exc_info() ) or an exception instance is provided, it is used; 如果提供了异常元组(以sys.exc_info()返回的格式)或异常实例,则使用它; otherwise, sys.exc_info() is called to get the exception information. 否则,调用sys.exc_info()以获取异常信息。

So do: 所以:

logger.warning("something raised an exception:", exc_info=True)

这是一个有效的(python 2.6.5)。

logger.critical("caught exception, traceback =", exc_info=True)

You can try this: 你可以试试这个:

from logging import getLogger

logger = getLogger('warning')

try:
    # Somethings that is wrong.

except Exception as exp:
    logger.warning("something raised an exception: " , exc_info=True)
    logger.warning("something raised an exception: {}".format(exp))  # another way

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Python 3中使用traceback记录异常对象 - How do I log an exception object with traceback in Python 3 在 Python 中记录带有回溯的异常 - Log exception with traceback in Python 如何让python函数返回异常回溯或结果? - How do I have a python function return an exception traceback, or the result? 如何在python中引发异常之前切片回溯? - How do I slice a traceback before raising an exception in python? 在标准输出上显示 INFO 级 python 日志而不更改源代码 - Showing INFO-level python logs on stdout without changing source code 如何在没有回溯的情况下进行异常处理? - How do I do the exception without the traceback? 如何使用日志记录模块将Python的unittest模块错误回溯重定向到日志文件? - How to redirect Python's unittest modules error traceback to log file using logging module? Python 日志记录 - 如何使用记录器配置文件为某些模块禁用或设置不同的日志记录级别? - Python logging - how do I disable or set different logging level for some modules, using the logger configuration file? 如何在python中收集警告级别的日志? - How in python I can collect log with level Warning? 如何设置 Python 日志级别? - How do I set the Python log level?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM