Skip to content

Python logger.exception()

  • by

Python logger.exception() will output a stack trace alongside the error message. In Python 3 you must call the logging.exception method just inside the except part. If you call this method in an arbitrary place you may get a bizarre exception. The docs alert about that.

try:
    main_loop()
except Exception:
    logger.exception("Fatal error in main loop")

Python logger exception()

A simple example code logs a Python error with debug information.

import logging

try:
    1 / 0
except ZeroDivisionError:
    logging.exception("Message")

Output:

Python logger exception()

The multiline message that shows up in your log might look like this:

Fatal error in main loop
Traceback (most recent call last):
  File "bigtarp.py", line 14, in
    main_loop()
  File "bigtarp.py", line 9, in main_loop
    print(foo(x))
  File "bigtarp.py", line 4, in foo
    return 10 // n
    ZeroDivisionError: integer division or modulo by zero

Do comment if you have any doubts or suggestions on this Python exception-handling topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *