From a246fcffee3ef40b9e201595d9081d092238fd5a Mon Sep 17 00:00:00 2001 From: AlexWaygood Date: Sun, 12 Jun 2022 19:20:52 +0100 Subject: [PATCH 1/2] Add `__setattr__` to `logging.LogRecord` --- stdlib/logging/__init__.pyi | 2 ++ test_cases/stdlib/test_logging.py | 14 ++++++++++++++ 2 files changed, 16 insertions(+) create mode 100644 test_cases/stdlib/test_logging.py diff --git a/stdlib/logging/__init__.pyi b/stdlib/logging/__init__.pyi index 8ed2f0b62417..6a8f66871a67 100644 --- a/stdlib/logging/__init__.pyi +++ b/stdlib/logging/__init__.pyi @@ -413,6 +413,8 @@ class LogRecord: sinfo: str | None = ..., ) -> None: ... def getMessage(self) -> str: ... + # Allows setting contextual information on LogRecord objects as per the docs, see #7833 + def __setattr__(self, __name: str, __value: Any) -> None: ... _L = TypeVar("_L", bound=Logger | LoggerAdapter[Any]) diff --git a/test_cases/stdlib/test_logging.py b/test_cases/stdlib/test_logging.py new file mode 100644 index 000000000000..f1fcd5814f11 --- /dev/null +++ b/test_cases/stdlib/test_logging.py @@ -0,0 +1,14 @@ +import logging +from typing import Any + +# This pattern comes from the logging docs, and should therefore pass a type checker +# See https://docs.python.org/3/library/logging.html#logrecord-objects + +old_factory = logging.getLogRecordFactory() + +def record_factory(*args: Any, **kwargs: Any) -> logging.LogRecord: + record = old_factory(*args, **kwargs) + record.custom_attribute = 0xdecafbad + return record + +logging.setLogRecordFactory(record_factory) From 9c52b36db241604e5b0dad59c19fe537f802c870 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 12 Jun 2022 18:22:44 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks --- test_cases/stdlib/test_logging.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test_cases/stdlib/test_logging.py b/test_cases/stdlib/test_logging.py index f1fcd5814f11..dd572538fd4e 100644 --- a/test_cases/stdlib/test_logging.py +++ b/test_cases/stdlib/test_logging.py @@ -6,9 +6,11 @@ old_factory = logging.getLogRecordFactory() + def record_factory(*args: Any, **kwargs: Any) -> logging.LogRecord: record = old_factory(*args, **kwargs) - record.custom_attribute = 0xdecafbad + record.custom_attribute = 0xDECAFBAD return record + logging.setLogRecordFactory(record_factory)