From 7e174ebac48ea1c2951da46c7bff35a2ae645dfe Mon Sep 17 00:00:00 2001 From: Bram Neijt Date: Thu, 19 Feb 2026 16:02:42 +0100 Subject: [PATCH] Log extra attributes as otel attributes --- src/lambda_otel_logging/logging.py | 14 +++++++++++++- tests/test_logging.py | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/lambda_otel_logging/logging.py b/src/lambda_otel_logging/logging.py index 06c4a89..02dba84 100644 --- a/src/lambda_otel_logging/logging.py +++ b/src/lambda_otel_logging/logging.py @@ -7,6 +7,13 @@ logger = logging.getLogger(__name__) +_STANDARD_LOG_RECORD_KEYS = frozenset( + logging.LogRecord( + name="", level=0, pathname="", lineno=0, msg="", args=(), exc_info=None + ).__dict__.keys() +) + + LoggingLevel: TypeAlias = ( Literal["CRITICAL"] | Literal["FATAL"] @@ -55,6 +62,11 @@ def format(self, record: logging.LogRecord) -> str: extra_attributes: dict[str, str] = record.__dict__.pop("otel_attributes", {}) + # Capture any extra attributes passed via logger.info(..., extra={...}) + for key, value in record.__dict__.items(): + if key not in _STANDARD_LOG_RECORD_KEYS and key not in extra_attributes: + extra_attributes[key] = value if isinstance(value, str) else repr(value) + if record.exc_info: extra_attributes["exception.stacktrace"] = ( logging.Formatter().formatException(record.exc_info) @@ -72,10 +84,10 @@ def format(self, record: logging.LogRecord) -> str: "name": record.name, }, "attributes": { + **extra_attributes, "code.file.path": record.pathname, "code.line.number": record.lineno, "code.function.name": record.funcName, - **extra_attributes, }, } return json_encode(record_dict).decode("utf-8") diff --git a/tests/test_logging.py b/tests/test_logging.py index 90616bc..b98eb0c 100644 --- a/tests/test_logging.py +++ b/tests/test_logging.py @@ -81,3 +81,21 @@ def test_should_log_object(capsys: CaptureFixture) -> None: assert ( "Encoding objects of type DataNotFoundError is unsupported" not in captured.err ) + + +def test_extra_attributes_included_in_log(capsys: CaptureFixture) -> None: + """Test that extra= kwargs are included in the structured log attributes.""" + logger = basic_config() + logger.info( + "test message with extras", + extra={"user.id": "123", "request.id": "abc-456", "count": 42}, + ) + + captured = capsys.readouterr() + output = captured.err + captured.out + decoded = msgspec.json.decode(output.strip()) + + assert decoded["body"] == "test message with extras" + assert decoded["attributes"]["user.id"] == "123" + assert decoded["attributes"]["request.id"] == "abc-456" + assert decoded["attributes"]["count"] == "42" # Non-strings are repr'd