Skip to content

Commit cee80a6

Browse files
authored
Restrict the logic for trace detection in logs (#519)
* restrict the logic for trace detection in logs * lint * lint * typo
1 parent 9656d13 commit cee80a6

File tree

2 files changed

+43
-3
lines changed

2 files changed

+43
-3
lines changed

aws/logs_monitoring/lambda_function.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -175,9 +175,19 @@ def extract_trace_payload(event):
175175
try:
176176
message = event["message"]
177177
obj = json.loads(event["message"])
178-
if not "traces" in obj or not isinstance(obj["traces"], list):
179-
return None
180-
return {"message": message, "tags": event[DD_CUSTOM_TAGS]}
178+
179+
obj_has_traces = "traces" in obj
180+
traces_is_a_list = isinstance(obj["traces"], list)
181+
# check that the log is not containing a trace array unrelated to Datadog
182+
trace_id_found = (
183+
len(obj["traces"]) > 0
184+
and len(obj["traces"][0]) > 0
185+
and obj["traces"][0][0]["trace_id"] is not None
186+
)
187+
188+
if obj_has_traces and traces_is_a_list and trace_id_found:
189+
return {"message": message, "tags": event[DD_CUSTOM_TAGS]}
190+
return None
181191
except Exception:
182192
return None
183193

aws/logs_monitoring/tests/test_lambda_function.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
extract_host_from_cloudtrails,
3030
extract_host_from_guardduty,
3131
extract_host_from_route53,
32+
extract_trace_payload,
3233
enrich,
3334
transform,
3435
split,
@@ -198,5 +199,34 @@ def test_datadog_forwarder(self, mock_get_s3_cache, mock_forward_metrics):
198199
del os.environ["DD_FETCH_LAMBDA_TAGS"]
199200

200201

202+
class TestLambdaFunctionExtractTracePayload(unittest.TestCase):
203+
def test_extract_trace_payload_none_no_trace(self):
204+
message_json = """{
205+
"key": "value"
206+
}"""
207+
self.assertEqual(extract_trace_payload({"message": message_json}), None)
208+
209+
def test_extract_trace_payload_none_exception(self):
210+
message_json = """{
211+
"invalid_json"
212+
}"""
213+
self.assertEqual(extract_trace_payload({"message": message_json}), None)
214+
215+
def test_extract_trace_payload_unrelated_datadog_trace(self):
216+
message_json = """{"traces":["I am a trace"]}"""
217+
self.assertEqual(extract_trace_payload({"message": message_json}), None)
218+
219+
def test_extract_trace_payload_valid_trace(self):
220+
message_json = """{"traces":[[{"trace_id":1234}]]}"""
221+
tags_json = """["key0:value", "key1:value1"]"""
222+
item = {
223+
"message": '{"traces":[[{"trace_id":1234}]]}',
224+
"tags": '["key0:value", "key1:value1"]',
225+
}
226+
self.assertEqual(
227+
extract_trace_payload({"message": message_json, "ddtags": tags_json}), item
228+
)
229+
230+
201231
if __name__ == "__main__":
202232
unittest.main()

0 commit comments

Comments
 (0)