Skip to content

LOG004 false positive #18044

@sk-

Description

@sk-

Summary

The preview rule LOG004 (log-exception-outside-except-handler) is producing a false positive when explicitly passing an exc_info argument.

The code below (playground link) reproduces the issue:

import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.exception("Test LOG004", exc_info=IndexError("test message"))

producing the output

test_logging.py:5:1: LOG004 `.exception()` call outside exception handlers
  |
3 | logging.basicConfig(level=logging.INFO)
4 | logger = logging.getLogger(__name__)
5 | logger.exception("Test LOG004", exc_info=IndexError("test message"))
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LOG004
  |
  = help: Replace with `.error()`

Found 1 error.
No fixes available (1 hidden fix can be enabled with the `--unsafe-fixes` option).

However, this code is perfectly valid and it outputs

ERROR:__main__:Test LOG004
IndexError: test message

Note that the justification for the rule states:

Calling .exception() outside of an exception handler attaches None as exception information, leading to confusing messages:

However in this case, the exception information is indeed attached because it was passed explicitly.

I could see why someone may prefer to just use error and avoid using exception in this case, but that IMO would be a stylistical rule similar to LOG007. Such rule could get some good reception as others have manifested that they never use logger.exception.

Version

0.11.9

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionAsking for support or clarification

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions