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

3

79

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.

Alloy answered 10/10, 2008 at 17:2 Comment(0)
R
127

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)
Reflex answered 10/10, 2008 at 21:49 Comment(2)
Note that the docs don't mention this explicitly for info, warning, error, etc. They just say "The arguments are interpreted as for debug()." -- which is why if you need to return to this later, that's where you should look for the above description of this behavior.Blunk
Does anyone have insight into whether this differs from just calling logger.exception, other than the log level being 'warning' ?Rank
R
6

Here is one that works (python 2.6.5).

logger.critical("caught exception, traceback =", exc_info=True)
Regeneration answered 5/2, 2011 at 19:53 Comment(0)
F
2

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
Fissure answered 23/4, 2018 at 7:18 Comment(3)
IIRC, these won't do the same thing. The first way logs a stack trace, the second way logs the name of the exception class for the exception that occurred. That's very different.Blunk
@BrianPeterson The purpose of the qeustion is to print exp. both mentioned logger method fulfill this. I tested it now.Fissure
The downside of the second call is that it always formats the message, even if it will not be logged because of how the logger is configured. The best is to format only when needed. BTW, to make the {}-formatting, it is necessary to set it on the Formatter object, see docs.python.org/3/library/logging.html#logging.Formatter, the default is the old-style %-formatting.Cambist

© 2022 - 2024 — McMap. All rights reserved.