0

Considering the following errornous function:

def inner():
    raise Exception("message")

If I run the function I get an error like:

Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py", line 364, in runcode
    coro = func()
           ^^^^^^
  File "<input>", line 1, in <module>
  File "<input>", line 2, in inner
Exception: message

Now I wish for logging purposes to get this kind of error messaging into code, what I tried was using traceback.format_exc() as well as unpacking sys.exc_info()

def outer():
    try:
        inner()
    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        print(exc_type)
        print(exc_obj)
        print(exc_tb)
        print(traceback.format_tb(exc_tb))
        print(traceback.format_exc())

which gives:

>>> outer()
<class 'Exception'>
message
<traceback object at 0x10affca00>
['  File "<input>", line 3, in outer\n', '  File "<input>", line 2, in inner\n']
Traceback (most recent call last):
  File "<input>", line 3, in outer
  File "<input>", line 2, in inner
Exception: message

While format_exc() correctly formats the latter part, it does not include the import "line" information

/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py", line 364, in runcode
    coro = func()

How would I get that information and log that?

2
  • It looks like you have run the code differently, once via the PyCharm debugger and once in the REPL. This explains why the PyCharm related part is missing. Commented Oct 25, 2024 at 5:52
  • @KlausD. even running inside the interactive python shell inside pycharm the debugger attaches? I didn't know that. Makes it more unlikely that the answer can be answered, however if I could emulate this outside pycharm that is still something I would like. Commented Oct 25, 2024 at 6:19

1 Answer 1

0

If you really do insist on printing it than you can abuse the logging module to just format the exception for you:

import logging
import sys

try:
    1/0
except Exception:
    s = logging.Formatter().formatException(sys.exc_info())
    print(s)

There is a better way though by using the logging module as it is really intended:

import logging

try:
    1/0
except Exception:
    logging.exception()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.