This rule raises an issue when logging.error() is used within an exception handler (except block) to log exception information.

Why is this an issue?

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:

When 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:

Using logging.error() in an exception handler means you’re either:

The logging.exception() method is specifically designed for this use case and is the established Python idiom for logging exceptions.

How to fix it

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.

Code examples

Noncompliant code example

import logging

try:
    raise ValueError("Invalid value")
except ValueError:
    logging.error("Exception occurred", exc_info=True)  # Noncompliant

Compliant solution

import logging

try:
    raise ValueError("Invalid value")
except ValueError:
    logging.exception("Exception occurred")

Resources

Documentation