Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(logger): strip xray_trace_id when explicitly disabled #2852

Merged
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
8 changes: 6 additions & 2 deletions aws_lambda_powertools/logging/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,12 @@ def _build_default_keys():
"timestamp": "%(asctime)s",
}

@staticmethod
def _get_latest_trace_id():
def _get_latest_trace_id(self):
xray_trace_id_key = self.log_format.get("xray_trace_id", "")
if xray_trace_id_key is None:
# key is explicitly disabled; ignore it. e.g., Logger(xray_trace_id=None)
return None

xray_trace_id = os.getenv(constants.XRAY_TRACE_ID_ENV)
return xray_trace_id.split(";")[0].replace("Root=", "") if xray_trace_id else None

Expand Down
21 changes: 21 additions & 0 deletions tests/functional/test_logger_powertools_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,27 @@ def test_log_dict_xray_is_updated_when_tracing_id_changes(stdout, monkeypatch, s
monkeypatch.delenv(name="_X_AMZN_TRACE_ID")


def test_log_dict_xray_is_not_present_when_explicitly_disabled(
stdout: io.StringIO,
monkeypatch: pytest.MonkeyPatch,
service_name: str,
):
# GIVEN a logger is initialized within a Lambda function with X-Ray enabled
# and X-Ray Trace ID key is explicitly disabled
trace_id = "1-5759e988-bd862e3fe1be46a994272793"
trace_header = f"Root={trace_id};Parent=53995c3f42cd8ad8;Sampled=1"
monkeypatch.setenv(name="_X_AMZN_TRACE_ID", value=trace_header)
logger = Logger(service=service_name, stream=stdout, xray_trace_id=None)

# WHEN logging a message
logger.info("foo")

log_dict: dict = json.loads(stdout.getvalue())

# THEN `xray_trace_id`` key should not be present
assert "xray_trace_id" not in log_dict


def test_log_custom_std_log_attribute(stdout, service_name):
# GIVEN a logger where we have a standard log attr process
# https://docs.python.org/3/library/logging.html#logrecord-attributes
Expand Down