Skip to content

Commit 7dbdd81

Browse files
authored
fix(logger): strip xray_trace_id when explicitly disabled (aws-powertools#2852)
1 parent c9976a6 commit 7dbdd81

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

aws_lambda_powertools/logging/formatter.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -236,8 +236,12 @@ def _build_default_keys():
236236
"timestamp": "%(asctime)s",
237237
}
238238

239-
@staticmethod
240-
def _get_latest_trace_id():
239+
def _get_latest_trace_id(self):
240+
xray_trace_id_key = self.log_format.get("xray_trace_id", "")
241+
if xray_trace_id_key is None:
242+
# key is explicitly disabled; ignore it. e.g., Logger(xray_trace_id=None)
243+
return None
244+
241245
xray_trace_id = os.getenv(constants.XRAY_TRACE_ID_ENV)
242246
return xray_trace_id.split(";")[0].replace("Root=", "") if xray_trace_id else None
243247

tests/functional/test_logger_powertools_formatter.py

+21
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,27 @@ def test_log_dict_xray_is_updated_when_tracing_id_changes(stdout, monkeypatch, s
251251
monkeypatch.delenv(name="_X_AMZN_TRACE_ID")
252252

253253

254+
def test_log_dict_xray_is_not_present_when_explicitly_disabled(
255+
stdout: io.StringIO,
256+
monkeypatch: pytest.MonkeyPatch,
257+
service_name: str,
258+
):
259+
# GIVEN a logger is initialized within a Lambda function with X-Ray enabled
260+
# and X-Ray Trace ID key is explicitly disabled
261+
trace_id = "1-5759e988-bd862e3fe1be46a994272793"
262+
trace_header = f"Root={trace_id};Parent=53995c3f42cd8ad8;Sampled=1"
263+
monkeypatch.setenv(name="_X_AMZN_TRACE_ID", value=trace_header)
264+
logger = Logger(service=service_name, stream=stdout, xray_trace_id=None)
265+
266+
# WHEN logging a message
267+
logger.info("foo")
268+
269+
log_dict: dict = json.loads(stdout.getvalue())
270+
271+
# THEN `xray_trace_id`` key should not be present
272+
assert "xray_trace_id" not in log_dict
273+
274+
254275
def test_log_custom_std_log_attribute(stdout, service_name):
255276
# GIVEN a logger where we have a standard log attr process
256277
# https://docs.python.org/3/library/logging.html#logrecord-attributes

0 commit comments

Comments
 (0)