Add __setattr__ to logging.LogRecord (#8064)

This commit is contained in:
Alex Waygood
2022-06-12 20:04:22 +01:00
committed by GitHub
parent 8bb18aa541
commit 1aa5663f9e
2 changed files with 18 additions and 0 deletions

View File

@@ -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])

View File

@@ -0,0 +1,16 @@
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)