This rule raises an issue when logging.error() is used within an exception handler (except block) to log exception
information.
When handling exceptions in Python, it’s important to capture not just the error message, but also the full traceback. The traceback shows the sequence of function calls that led to the exception, which is essential for understanding what went wrong and where.
The logging module provides two methods that might seem similar:
logging.error(): Logs an error message at the ERROR levellogging.exception(): Logs an error message at the ERROR level AND automatically includes the full exception tracebackWhen you’re inside an exception handler (except block), you’re dealing with an exception that just occurred. In this context,
logging.exception() is the appropriate choice because:
exc_info=TrueUsing logging.error() in an exception handler means you’re either:
exc_info=True), making debugging much harderexc_info=True) when a simpler, more idiomatic option existsThe logging.exception() method is specifically designed for this use case and is the established Python idiom for logging
exceptions.
Replace logging.error() with logging.exception() when logging within an exception handler. If you were using
exc_info=True, you can remove it since logging.exception() includes traceback information by default.
import logging
try:
raise ValueError("Invalid value")
except ValueError:
logging.error("Exception occurred", exc_info=True) # Noncompliant
import logging
try:
raise ValueError("Invalid value")
except ValueError:
logging.exception("Exception occurred")