Skip to content

Commit faf838f

Browse files
committed
Updated the tests, serialization method and renamed the parameter
1 parent c57a77b commit faf838f

File tree

8 files changed

+56
-25
lines changed

8 files changed

+56
-25
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,7 @@ dmypy.json
252252
.pyre/
253253

254254
### VisualStudioCode ###
255+
.vscode
255256
.vscode/*
256257
!.vscode/tasks.json
257258
!.vscode/launch.json

aws_lambda_powertools/logging/formatter.py

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import inspect
4+
import sys
45
import json
56
import logging
67
import os
@@ -81,7 +82,7 @@ def __init__(
8182
log_record_order: List[str] | None = None,
8283
utc: bool = False,
8384
use_rfc3339: bool = False,
84-
include_stacktrace: bool = None,
85+
serialize_stacktrace: bool = None,
8586
**kwargs,
8687
) -> None:
8788
"""Return a LambdaPowertoolsFormatter instance.
@@ -153,8 +154,8 @@ def __init__(
153154
self.keys_combined = {**self._build_default_keys(), **kwargs}
154155
self.log_format.update(**self.keys_combined)
155156

156-
self.include_stacktrace = resolve_truthy_env_var_choice(env=os.getenv(constants.POWERTOOLS_STACKTRACE_ENV, "false"),
157-
choice=include_stacktrace,
157+
self.serialize_stacktrace = resolve_truthy_env_var_choice(env=os.getenv(constants.POWERTOOLS_STACKTRACE_ENV, "false"),
158+
choice=serialize_stacktrace,
158159
)
159160

160161
super().__init__(datefmt=self.datefmt)
@@ -163,27 +164,44 @@ def serialize(self, log: LogRecord) -> str:
163164
"""Serialize structured log dict to JSON str"""
164165
return self.json_serializer(log)
165166

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__)]
167+
# def serialize_traceback(self, e: Exception) -> list:
168+
# return [{"file": fs.filename,
169+
# "line": fs.lineno,
170+
# "column": fs.colno,
171+
# "function": fs.name,
172+
# "statement": fs.line
173+
# } for fs in traceback.extract_tb(e.__traceback__)]
174+
175+
def serialize_traceback(self, log_record: logging.LogRecord) -> list:
176+
exception_info = {
177+
"type": log_record.exc_info[0].__name__,
178+
"value": log_record.exc_info[1],
179+
"module": log_record.exc_info[1].__class__.__module__,
180+
"frames": []
181+
}
182+
183+
exception_info["frames"] = [{
184+
"file": fs.filename,
185+
"line": fs.lineno,
186+
"function": fs.name,
187+
"statement": fs.line
188+
} for fs in traceback.extract_tb(log_record.exc_info[2])]
173189

190+
return exception_info
174191

175192
def format(self, record: logging.LogRecord) -> str: # noqa: A003
176193
"""Format logging record as structured JSON str"""
177194
formatted_log = self._extract_log_keys(log_record=record)
178195
formatted_log["message"] = self._extract_log_message(log_record=record)
179196

180-
if self.include_stacktrace:
197+
if self.serialize_stacktrace:
181198
# Generate the traceback from the traceback library
182-
formatted_log["stack_trace"] = self.serialize_traceback(record.msg) #JSR
199+
formatted_log["stack_trace"] = self.serialize_traceback(log_record=record)
183200

184201
# exception and exception_name fields can be added as extra key
185202
# in any log level, we try to extract and use them first
186203
extracted_exception, extracted_exception_name = self._extract_log_exception(log_record=record)
204+
formatted_log["record"] = record
187205
formatted_log["exception"] = formatted_log.get("exception", extracted_exception)
188206
formatted_log["exception_name"] = formatted_log.get("exception_name", extracted_exception_name)
189207
formatted_log["xray_trace_id"] = self._get_latest_trace_id()

aws_lambda_powertools/logging/logger.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,7 @@ def __init__(
220220
log_record_order: Optional[List[str]] = None,
221221
utc: bool = False,
222222
use_rfc3339: bool = False,
223+
serialize_stacktrace: bool = None,
223224
**kwargs,
224225
) -> None:
225226
self.service = resolve_env_var_choice(
@@ -253,6 +254,7 @@ def __init__(
253254
"log_record_order": log_record_order,
254255
"utc": utc,
255256
"use_rfc3339": use_rfc3339,
257+
"serialize_stacktrace": serialize_stacktrace
256258
}
257259

258260
self._init_logger(formatter_options=formatter_options, log_level=level, **kwargs)

aws_lambda_powertools/shared/constants.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,4 @@
4343
POWERTOOLS_DEV_ENV: str = "POWERTOOLS_DEV"
4444
POWERTOOLS_DEBUG_ENV: str = "POWERTOOLS_DEBUG"
4545

46-
POWERTOOLS_STACKTRACE_ENV: str = "POWERTOOLS_LOGGER_ENHANCED_STACKTRACE"
46+
POWERTOOLS_STACKTRACE_ENV: str = "POWERTOOLS_LOGGER_SERIALIZE_STACKTRACE"

docs/core/logger.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ Logger can optionally log uncaught exceptions by setting `log_uncaught_exception
321321

322322
#### Stack trace logging
323323

324-
Logger can optionally log the full stack trace as JSON by setting `logger_formatter=LambdaPowertoolsFormatter(include_stacktrace=True)` at initialization. Optionally, setting the `POWERTOOLS_LOGGER_ENHANCED_STACKTRACE` environment variable to `true` will include stacktrace information in the logs.
324+
Logger can optionally log the full stack trace as JSON by setting `logger_formatter=LambdaPowertoolsFormatter(serialize_stacktrace=True)` at initialization. Optionally, setting the `POWERTOOLS_LOGGER_SERIALIZE_STACKTRACE` environment variable to `true` will include stacktrace information in the logs.
325325

326326
=== "logging_stacktrace.py"
327327

@@ -368,7 +368,7 @@ The following environment variables are available to configure Logger at a globa
368368
| **Event Logging** | Whether to log the incoming event. | `POWERTOOLS_LOGGER_LOG_EVENT` | `false` |
369369
| **Debug Sample Rate** | Sets the debug log sampling. | `POWERTOOLS_LOGGER_SAMPLE_RATE` | `0` |
370370
| **Disable Deduplication** | Disables log deduplication filter protection to use Pytest Live Log feature. | `POWERTOOLS_LOG_DEDUPLICATION_DISABLED` | `false` |
371-
| **Include Stack Trace** | Includes JSON formatted stack trace in the log output. | `POWERTOOLS_LOGGER_ENHANCED_STACKTRACE` | `false` |
371+
| **Include Stack Trace** | Includes JSON formatted stack trace in the log output. | `POWERTOOLS_LOGGER_SERIALIZE_STACKTRACE` | `false` |
372372

373373
[`POWERTOOLS_LOGGER_LOG_EVENT`](#logging-incoming-event) can also be set on a per-method basis, and [`POWERTOOLS_LOGGER_SAMPLE_RATE`](#sampling-debug-logs) on a per-instance basis. These parameter values will override the environment variable value.
374374

docs/index.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -723,7 +723,7 @@ Core utilities such as Tracing, Logging, Metrics, and Event Handler will be avai
723723
| **POWERTOOLS_PARAMETERS_SSM_DECRYPT** | Sets whether to decrypt or not values retrieved from AWS SSM Parameters Store | [Parameters](./utilities/parameters.md#ssmprovider){target="_blank"} | `false` |
724724
| **POWERTOOLS_DEV** | Increases verbosity across utilities | Multiple; see [POWERTOOLS_DEV effect below](#optimizing-for-non-production-environments) | `false` |
725725
| **LOG_LEVEL** | Sets logging level | [Logging](./core/logger.md){target="_blank"} | `INFO` |
726-
| **POWERTOOLS_LOGGER_ENHANCED_STACKTRACE** | Include JSON formatted stack trace in log message | [Logging](./core/logger.md){target="_blank"} | `false` |
726+
| **POWERTOOLS_LOGGER_SERIALIZE_STACKTRACE** | Include JSON formatted stack trace in log message | [Logging](./core/logger.md){target="_blank"} | `false` |
727727

728728
### Optimizing for non-production environments
729729

examples/logger/src/logging_stacktrace.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from aws_lambda_powertools.logging.formatter import LambdaPowertoolsFormatter
66

77
ENDPOINT = "http://httpbin.org/status/500"
8-
logger = Logger(logger_formatter=LambdaPowertoolsFormatter(include_stacktrace=True))
8+
logger = Logger(logger_formatter=LambdaPowertoolsFormatter(serialize_stacktrace=True))
99

1010

1111
def lambda_handler(event: dict, context: LambdaContext) -> str:

tests/functional/test_logger.py

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -964,18 +964,18 @@ def test_logger_logs_no_stack_trace_without_parameter(stdout):
964964
logger = Logger(stream=stdout)
965965

966966
try:
967-
val = 1 + "someString"
967+
raise ValueError("Something went wrong")
968968
except Exception as e:
969969
logger.exception(e)
970970

971971
log = capture_logging_output(stdout)
972972
assert "stack_trace" not in log
973973

974974
def test_logger_logs_stack_trace_with_parameter(stdout):
975-
logger = Logger(stream=stdout, logger_formatter=LambdaPowertoolsFormatter(include_stacktrace=True))
975+
logger = Logger(stream=stdout, logger_formatter=LambdaPowertoolsFormatter(serialize_stacktrace=True))
976976

977977
try:
978-
val = 1 + "someString"
978+
raise ValueError("Something went wrong")
979979
except Exception as e:
980980
logger.exception(e)
981981

@@ -987,20 +987,19 @@ def test_logger_logs_stack_trace_with_env_var(stdout, monkeypatch: pytest.Monkey
987987
logger = Logger(stream=stdout)
988988

989989
try:
990-
val = 1 + "someString"
990+
raise ValueError("Something went wrong")
991991
except Exception as e:
992992
logger.exception(e)
993993

994994
log = capture_logging_output(stdout)
995995
assert "stack_trace" in log
996996

997-
998997
def test_logger_logs_no_stack_trace_with_env_var(stdout, monkeypatch: pytest.MonkeyPatch):
999998
monkeypatch.setenv(constants.POWERTOOLS_STACKTRACE_ENV, "false")
1000999
logger = Logger(stream=stdout)
10011000

10021001
try:
1003-
val = 1 + "someString"
1002+
raise ValueError("Something went wrong")
10041003
except Exception as e:
10051004
logger.exception(e)
10061005

@@ -1009,12 +1008,23 @@ def test_logger_logs_no_stack_trace_with_env_var(stdout, monkeypatch: pytest.Mon
10091008

10101009
def test_logger_logs_no_stack_trace_with_parameter_override(stdout, monkeypatch: pytest.MonkeyPatch):
10111010
monkeypatch.setenv(constants.POWERTOOLS_STACKTRACE_ENV, "true")
1012-
logger = Logger(stream=stdout, logger_formatter=LambdaPowertoolsFormatter(include_stacktrace=False))
1011+
logger = Logger(stream=stdout, logger_formatter=LambdaPowertoolsFormatter(serialize_stacktrace=False))
10131012

10141013
try:
1015-
val = 1 + "someString"
1014+
raise ValueError("Something went wrong")
10161015
except Exception as e:
10171016
logger.exception(e)
10181017

10191018
log = capture_logging_output(stdout)
10201019
assert "stack_trace" not in log
1020+
1021+
def test_logger_logs_stack_trace_with_logger_parameter(stdout):
1022+
logger = Logger(stream=stdout, serialize_stacktrace=True)
1023+
1024+
try:
1025+
raise ValueError("Something went wrong")
1026+
except Exception as e:
1027+
logger.exception(e)
1028+
1029+
log = capture_logging_output(stdout)
1030+
assert "stack_trace" in log.keys()

0 commit comments

Comments
 (0)