Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/lambda_otel_logging/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down Expand Up @@ -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)
Expand All @@ -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")
Expand Down
18 changes: 18 additions & 0 deletions tests/test_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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