ruff icon indicating copy to clipboard operation
ruff copied to clipboard

Feature request: G101 logging-extra-attr-clash (or a new, similar rule) to detect (potentially) unsafe dict unpacking

Open roikoren755 opened this issue 1 year ago • 3 comments

First of all, I'd like to thank you for a great and easy-to-use linter 🥳

I've been running into issues lately where logging calls would fail, because I unpack some dict in the extra parameter to logging methods (or directly put a variable there), and that dict has a name key, for example.

Ruff doesn't catch these issues, and I thought a good rule (or extension to one of the existing flake8-logging-format rules) could catch these issues and warn about them. Knowing exactly when a bad argument will appear can be difficult, like in calls to pydantic classes' dict method, but I think warning on all places that pass an object directly to the extra parameter or unpack a dict inside it is still a good idea.

What do you think? I would also be willing to work on a PR for this, though my rust skills aren't as sharp as I'd like them to be for this 😅

roikoren755 avatar May 28 '23 12:05 roikoren755

Thank you :) Do you mind including an example snippet that demonstrates the problem? (Is it that the unpacked dictionary keys are also themselves valid arguments to logging calls?)

charliermarsh avatar May 28 '23 22:05 charliermarsh

Sorry, should have included examples in the original message. Yes, the problem is as you stated it.

The following is correctly flagged by ruff G101:

import logging

logger = logging.getLogger()
logger.info("", extra={"name": "fails"})

While the following aren't caught:

logger.info("", extra={**{"name": "fails"}})
extra = {"name": "fails"}
logger.info("", extra={**extra})
logger.info("", extra=extra)

from pydantic import BaseModel

class PydanticFail(BaseModel):
    name: str = "fails"

logger.info("", extra=PydanticFail().dict())
logger.info("", extra={**PydanticFail().dict()})

roikoren755 avatar May 29 '23 07:05 roikoren755

+1 Just hit the same issue but passing a TypedDict to extra.

regoawt avatar May 05 '24 17:05 regoawt