Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I log a Python error with debug information?

I am printing Python exception messages to a log file with logging.error:

import logging try:     1/0 except ZeroDivisionError as e:     logging.error(e)  # ERROR:root:division by zero 

Is it possible to print more detailed information about the exception and the code that generated it than just the exception string? Things like line numbers or stack traces would be great.

like image 586
probably at the beach Avatar asked Mar 04 '11 09:03

probably at the beach


People also ask

What is Python log debugging?

logging.debug() Diagnose problems, show detailed information. The logging module sets the default level at WARNING , so WARNING , ERROR , and CRITICAL will all be logged by default.


2 Answers

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."

like image 67
SiggyF Avatar answered Sep 20 '22 13:09

SiggyF


Using exc_info options may be better, to allow you to choose the error level (if you use exception, it will always be at the error level):

try:     # do something here except Exception as e:     logging.critical(e, exc_info=True)  # log exception info at CRITICAL log level 
like image 45
flycee Avatar answered Sep 22 '22 13:09

flycee