How to Log a Python Error with Debug Information

How do I log a Python error with debug information?

logger.exception will output a stack trace alongside the error message.

For example:

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

Output:

ERROR:root:message
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

@Paulo Cheque notes, "be aware that 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."

How to log python exception?

In Python 3.5 you can pass exception instance in exc_info argument:

import logging
try:
1/0
except Exception as e:
logging.error('Error at %s', 'division', exc_info=e)

Log exception with traceback in Python

Use logging.exception from within the except: handler/block to log the current exception along with the trace information, prepended with a message.

import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)

logging.debug('This message should go to the log file')

try:
run_my_stuff()
except:
logging.exception('Got exception on main handler')
raise

Now looking at the log file, /tmp/logging_example.out:

DEBUG:root:This message should go to the log file
ERROR:root:Got exception on main handler
Traceback (most recent call last):
File "/tmp/teste.py", line 9, in <module>
run_my_stuff()
NameError: name 'run_my_stuff' is not defined

python logging print traceback only in debug

I'd use a combination of exc_info and .getEffectiveLevel:

try:
...
except FileNotFoundError as ex:
logger.error(ex, exc_info=log.getEffectiveLevel() == logging.DEBUG)

This way, the exception itself (FileNotFoundError) is always logged, but the stacktrace will only be logged if log level is debug.

Python Logging: INFO,DEBUG Logs not displayed

  1. You're setting log level for stream handler while you have to do it for logger itself (logger_obj in your case). Handler is used to apply additional filters to logs, but they are first filtered by logger itself.

  2. DEBUG > INFO, so you have to set level to DEBUG, not INFO (If you want to see all logs).

in short, use:

logger_obj.setLevel(logging.DEBUG)


Related Topics



Leave a reply



Submit