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.
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).
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.
From the logging documentation:
There are three keyword arguments in
kwargs
which are inspected:exc_info
,stack_info
, andextra
.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 bysys.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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With