How do I log an exception at warning- or info-leve

2019-02-01 09:09发布

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.

7条回答
欢心
2楼-- · 2019-02-01 09:25

Here is one that works (python 2.6.5).

logger.critical("caught exception, traceback =", exc_info=True)
查看更多
放我归山
3楼-- · 2019-02-01 09:29

From the logging documentation:

There are three keyword arguments in kwargs which are inspected: exc_info, stack_info, and extra.

If exc_info does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by sys.exc_info()) or an exception instance is provided, it is used; otherwise, sys.exc_info() is called to get the exception information.

So do:

logger.warning("something raised an exception:", exc_info=True)
查看更多
Lonely孤独者°
4楼-- · 2019-02-01 09:32

Try using Logger.exception.

Logger.exception() creates a log message similar to Logger.error(). The difference is that Logger.exception() dumps a stack trace along with it. Call this method only from an exception handler.

查看更多
聊天终结者
5楼-- · 2019-02-01 09:36

You can try this:

from logging import getLogger

logger = getLogger('warn')

try:
    # Somethings that is wrong.

except Exception as exp:
    logger.warn("something raised an exception: " , exc_info=True)
    logger.warn("something raised an exception: {}".format(exp))  # another way
查看更多
成全新的幸福
6楼-- · 2019-02-01 09:39

I was able to display log messages in a exception block with the following code snippet:

# basicConfig have to be the first statement
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("componet")
try:
    raise BaseException
except BaseException:
    logger.warning("something raised an exception: ",exc_info=True)
    logger.info("something raised an exception: " ,exc_info=True)
查看更多
可以哭但决不认输i
7楼-- · 2019-02-01 09:44

Use Logger.exception().

try:
   #Something...
except BaseException, excep:
   logger = logging.getLogger("component")
   logger.exception("something raised an exception")
查看更多
登录 后发表回答