Skip to content

Commit 1aa5663

Browse files
authored
Add __setattr__ to logging.LogRecord (#8064)
1 parent 8bb18aa commit 1aa5663

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

stdlib/logging/__init__.pyi

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,8 @@ class LogRecord:
413413
sinfo: str | None = ...,
414414
) -> None: ...
415415
def getMessage(self) -> str: ...
416+
# Allows setting contextual information on LogRecord objects as per the docs, see #7833
417+
def __setattr__(self, __name: str, __value: Any) -> None: ...
416418

417419
_L = TypeVar("_L", bound=Logger | LoggerAdapter[Any])
418420

test_cases/stdlib/test_logging.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import logging
2+
from typing import Any
3+
4+
# This pattern comes from the logging docs, and should therefore pass a type checker
5+
# See https://docs.python.org/3/library/logging.html#logrecord-objects
6+
7+
old_factory = logging.getLogRecordFactory()
8+
9+
10+
def record_factory(*args: Any, **kwargs: Any) -> logging.LogRecord:
11+
record = old_factory(*args, **kwargs)
12+
record.custom_attribute = 0xDECAFBAD
13+
return record
14+
15+
16+
logging.setLogRecordFactory(record_factory)

0 commit comments

Comments
 (0)