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

PythonExceptionLogging

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

Here is one that works (python 2.6.5).

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

Solution 3 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMorten Holdflod MøllerView Question on Stackoverflow
Solution 1 - PythonDouglas LeederView Answer on Stackoverflow
Solution 2 - PythonScubahubbyView Answer on Stackoverflow
Solution 3 - PythonBenyamin JafariView Answer on Stackoverflow