Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 598
Morten Holdflod Møller Avatar asked Oct 10 '08 17:10

Morten Holdflod Møller


People also ask

How do I log exception traceback in Python?

For your last code block, rather than initializing a StringIO and printing the exception to it, you can just call logger. error(traceback. format_tb()) (or format_exc() if you want the exception info too).

How do you log an exception in Python?

To log an exception in Python we can use logging module and through that we can log the error. Logging an exception in python with an error can be done in the logging. exception() method. This function logs a message with level ERROR on this logger.


1 Answers

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) 
like image 65
Douglas Leeder Avatar answered Sep 28 '22 11:09

Douglas Leeder