Skip to content
Open
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

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions aws_lambda_powertools/logging/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,8 @@ def format(self, record: logging.LogRecord) -> str: # noqa: A003
if self.serialize_stacktrace:
# Generate the traceback from the traceback library
formatted_log["stack_trace"] = self._serialize_stacktrace(log_record=record)
# Set only when the caller passes stack_info=True; None is stripped below
formatted_log["stack_info"] = formatted_log.get("stack_info", record.stack_info)
formatted_log["xray_trace_id"] = self._get_latest_trace_id()
formatted_log = self._strip_none_records(records=formatted_log)

Expand Down
16 changes: 16 additions & 0 deletions docs/core/logger.md
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,22 @@ By default, the Logger will automatically include the full stack trace in JSON f
--8<-- "examples/logger/src/logging_stacktrace_output.json"
```

#### Logging the call stack

To see how your code reached a log line without raising an exception, pass `stack_info=True`, as in the standard `logging` library. Logger adds the call stack as a string under the `stack_info` key. The key is only present when you ask for it.

=== "logging_stack_info.py"

```python hl_lines="8"
--8<-- "examples/logger/src/logging_stack_info.py"
```

=== "logging_stack_info_output.json"

```json hl_lines="8"
--8<-- "examples/logger/src/logging_stack_info_output.json"
```

#### Adding exception notes

You can add notes to exceptions, which `logger.exception` propagates via a new `exception_notes` key in the log line. This works only in [Python 3.11 and later](https://peps.python.org/pep-0678/){target="_blank" rel="nofollow"}.
Expand Down
14 changes: 14 additions & 0 deletions examples/logger/src/logging_stack_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from aws_lambda_powertools import Logger
from aws_lambda_powertools.utilities.typing import LambdaContext

logger = Logger()


def charge_customer(order_id: str) -> None:
logger.info("Charging customer", order_id=order_id, stack_info=True)


def lambda_handler(event: dict, context: LambdaContext) -> str:
charge_customer(order_id=event["order_id"])

return "hello world"
9 changes: 9 additions & 0 deletions examples/logger/src/logging_stack_info_output.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"level": "INFO",
"location": "charge_customer:8",
"message": "Charging customer",
"timestamp": "2026-12-02 14:18:49,255+0000",
"service": "service_undefined",
"order_id": "ord-123",
"stack_info": "Stack (most recent call last):\n File \"/var/task/app.py\", line 12, in lambda_handler\n charge_customer(order_id=event[\"order_id\"])\n File \"/var/task/app.py\", line 8, in charge_customer\n logger.info(\"Charging customer\", order_id=order_id, stack_info=True)"
}
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,34 @@ def handler(event, context):
assert "stack_trace" in log


def test_logger_logs_stack_info_when_requested(service_name, stdout):
# GIVEN a Logger instance
logger = Logger(service=service_name, stream=stdout)

# WHEN logging with stack_info=True
def charge():
logger.info("charging", stack_info=True)

charge()

# THEN the call stack is included under "stack_info", as the standard library prints it
log = capture_logging_output(stdout)[0]
assert log["stack_info"].startswith("Stack (most recent call last):")
assert "in charge" in log["stack_info"]


def test_logger_omits_stack_info_by_default(service_name, stdout):
# GIVEN a Logger instance
logger = Logger(service=service_name, stream=stdout)

# WHEN logging without stack_info
logger.info("charging")

# THEN no "stack_info" key is added
log = capture_logging_output(stdout)[0]
assert "stack_info" not in log


def test_logger_logs_stack_trace_with_formatter_non_default_value(service_name, stdout):
# GIVEN a Logger instance with serialize_stacktrace = False
logger = Logger(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -826,3 +826,24 @@ def test_logger_buffer_logs_immediately_without_trace_id(stdout, service_name, m
logger.flush_buffer()

assert len(capture_multiple_logging_statements_output(stdout)) == 1


def test_logger_buffer_keeps_stack_info_on_flush(stdout, service_name, monkeypatch):
monkeypatch.setenv(constants.XRAY_TRACE_ID_ENV, "1-67c39786-5908a82a246fb67f3089263f")

# GIVEN A logger configured with a buffer
logger_buffer_config = LoggerBufferConfig(max_bytes=10240, buffer_at_verbosity="DEBUG")
logger = Logger(level="DEBUG", service=service_name, stream=stdout, buffer_config=logger_buffer_config)

# WHEN a buffered debug line asks for stack_info and the buffer is flushed
def charge():
logger.debug("charging", stack_info=True)

charge()
logger.flush_buffer()

# THEN the flushed line includes the call stack
log = capture_multiple_logging_statements_output(stdout)
assert log[0]["message"] == "charging"
assert log[0]["stack_info"].startswith("Stack (most recent call last):")
assert "in charge" in log[0]["stack_info"]