Search code examples
pythonvariablesloggingerror-loggingtry-except

Python Try-Except: How to variabilize Logging.info?


This would be the funniest thing you see all day. But here it is. How do I turn my printed-out exception message into a variable, so I can globalize and update them into my database?

Here is the analogy:

try:

except Exception as e:
        logging.error(traceback.format_exc())

This is what I'm currently doing:

try:

except Exception as e:
        logging.error(traceback.format_exc())
        loginerror = logging.error(traceback.format_exc())
        print str(loginerror)

So,I basically get None, because clearly it hasn't been variablized:

None

If needed, here's what my exception message prints out:

2018-08-10 09:38:00,009 - root - ERROR - Traceback (most recent call last):
  File "C:\jobtech-crawlers\crawler_parttimejobs.py", line 122, in dump_parttimejobs
    response = requests_retry_session().get(url=linkWqery)
NameError: global name 'linkWqery' is not defined

Solution

  • If you remove the logging.error, it returns a string of the error message.

    try:
        print(0/0)
    except Exception as e:
        x = traceback.format_exc()
    
    print(x)