Skip to content

Commit 163b908

Browse files
committed
Added optional stack trace to exception logging. Issue 1268
1 parent 735d3ee commit 163b908

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

aws_lambda_powertools/logging/formatter.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,14 @@
55
import logging
66
import os
77
import time
8+
import traceback
89
from abc import ABCMeta, abstractmethod
910
from datetime import datetime, timezone
1011
from functools import partial
1112
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
13+
from ..shared.functions import (
14+
resolve_truthy_env_var_choice
15+
)
1216

1317
from aws_lambda_powertools.logging.types import LogRecord
1418
from aws_lambda_powertools.shared import constants
@@ -77,6 +81,7 @@ def __init__(
7781
log_record_order: List[str] | None = None,
7882
utc: bool = False,
7983
use_rfc3339: bool = False,
84+
include_traceback: bool = None,
8085
**kwargs,
8186
) -> None:
8287
"""Return a LambdaPowertoolsFormatter instance.
@@ -148,16 +153,34 @@ def __init__(
148153
self.keys_combined = {**self._build_default_keys(), **kwargs}
149154
self.log_format.update(**self.keys_combined)
150155

156+
self.include_traceback = resolve_truthy_env_var_choice(env=os.getenv(constants.POWERTOOLS_TRACEBACK_ENV, "false"),
157+
choice=include_traceback,
158+
)
159+
151160
super().__init__(datefmt=self.datefmt)
152161

153162
def serialize(self, log: LogRecord) -> str:
154163
"""Serialize structured log dict to JSON str"""
155164
return self.json_serializer(log)
165+
166+
def serialize_traceback(self, e: Exception) -> list:
167+
return [{"File": fs.filename,
168+
"Line": fs.lineno,
169+
"Column": fs.colno,
170+
"Function": fs.name,
171+
"Statement": fs.line
172+
} for fs in traceback.extract_tb(e.__traceback__)]
173+
156174

157175
def format(self, record: logging.LogRecord) -> str: # noqa: A003
158176
"""Format logging record as structured JSON str"""
159177
formatted_log = self._extract_log_keys(log_record=record)
160178
formatted_log["message"] = self._extract_log_message(log_record=record)
179+
180+
if self.include_traceback:
181+
# Generate the traceback from the traceback library
182+
formatted_log["stack_trace"] = self.serialize_traceback(record.msg) #JSR
183+
161184
# exception and exception_name fields can be added as extra key
162185
# in any log level, we try to extract and use them first
163186
extracted_exception, extracted_exception_name = self._extract_log_exception(log_record=record)

aws_lambda_powertools/shared/constants.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,5 @@
4242

4343
POWERTOOLS_DEV_ENV: str = "POWERTOOLS_DEV"
4444
POWERTOOLS_DEBUG_ENV: str = "POWERTOOLS_DEBUG"
45+
46+
POWERTOOLS_TRACEBACK_ENV: str = "POWERTOOLS_LOGGER_ENHANCED_TRACEBACK"

0 commit comments

Comments
 (0)