Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(lambda): emit CloudWatch Logs for API Gateway-triggered invocations (#449)

Stephan Mielked9a46af3a450
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index cdf0a115..24f08816 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -578,6 +578,9 @@ class Worker:
if response.get("status") == "error":
self._proc = None
response["cold_start"] = cold
+ # Brief pause so in-flight stderr lines from the OS pipe buffer
+ # reach the queue before we drain it.
+ time.sleep(0.05)
response["log"] = self._drain_stderr()
return response
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index f0435f3e..24e24286 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -472,7 +472,6 @@ def _path_matches(route_path: str, request_path: str) -> bool:
async def _invoke_lambda_proxy(integration, api_id, stage, path, method, headers, body, query_params, route_key="$default", path_params=None):
"""Invoke a Lambda function using the API Gateway v2 proxy event format."""
- from ministack.core.lambda_runtime import get_or_create_worker
from ministack.services import lambda_svc
# integrationUri from Terraform / real AWS is wrapped:
@@ -522,19 +521,16 @@ async def _invoke_lambda_proxy(integration, api_id, stage, path, method, headers
"isBase64Encoded": False,
}
- code_zip = func_data.get("code_zip")
- runtime = func_config.get("Runtime", "")
- if code_zip and runtime.startswith(("python", "nodejs")):
- # Key the worker by name+qualifier so versioned / aliased invocations
- # use their own cached process, matching Lambda.Invoke semantics.
- worker_key = f"{func_name}:{qualifier}" if qualifier else func_name
- worker = get_or_create_worker(worker_key, func_config, code_zip)
- result = await asyncio.to_thread(worker.invoke, event, new_uuid())
- if result.get("status") == "error":
- return 502, {"Content-Type": "application/json"}, json.dumps({"message": result.get("error")}).encode()
- lambda_response = result.get("result", {})
- else:
- lambda_response = {"statusCode": 200, "body": "Mock response"}
+ # Route through the central _execute_function dispatcher so CloudWatch
+ # Logs emission and Docker log output work for API Gateway invocations.
+ exec_record = {"config": func_config, "code_zip": func_data.get("code_zip")}
+ result = await asyncio.to_thread(lambda_svc._execute_function, exec_record, event)
+ if result.get("error"):
+ error_msg = result.get("body", {})
+ if isinstance(error_msg, dict):
+ error_msg = error_msg.get("errorMessage", "Lambda invocation error")
+ return 502, {"Content-Type": "application/json"}, json.dumps({"message": error_msg}).encode()
+ lambda_response = result.get("body", {})
status = lambda_response.get("statusCode", 200)
resp_headers = {"Content-Type": "application/json"}
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 3516837c..9a533ee7 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -435,7 +435,6 @@ async def _call_lambda(func_name, event, qualifier=None):
``qualifier`` may be a version number or alias name; aliases resolve to
their target version via ``_get_func_record_for_qualifier`` so aliased
integration URIs (arn:...:function:<name>:<alias>) invoke correctly (#407)."""
- from ministack.core.lambda_runtime import get_or_create_worker
from ministack.services import lambda_svc
func_data, func_config = lambda_svc._get_func_record_for_qualifier(func_name, qualifier)
@@ -443,17 +442,16 @@ async def _call_lambda(func_name, event, qualifier=None):
label = f"{func_name}:{qualifier}" if qualifier else func_name
return None, f"Lambda function '{label}' not found"
- code_zip = func_data.get("code_zip")
- runtime = func_config.get("Runtime", "")
- if code_zip and runtime.startswith(("python", "nodejs")):
- worker_key = f"{func_name}:{qualifier}" if qualifier else func_name
- worker = get_or_create_worker(worker_key, func_config, code_zip)
- result = await asyncio.to_thread(worker.invoke, event, new_uuid())
- if result.get("status") == "error":
- return None, result.get("error", "Lambda invocation error")
- return result.get("result", {}), None
- else:
- return {"statusCode": 200, "body": "Mock response"}, None
+ # Route through the central _execute_function dispatcher so CloudWatch
+ # Logs emission and Docker log output work for API Gateway invocations.
+ exec_record = {"config": func_config, "code_zip": func_data.get("code_zip")}
+ result = await asyncio.to_thread(lambda_svc._execute_function, exec_record, event)
+ if result.get("error"):
+ error_msg = result.get("body", {})
+ if isinstance(error_msg, dict):
+ error_msg = error_msg.get("errorMessage", "Lambda invocation error")
+ return None, error_msg
+ return result.get("body", {}), None
# ---- Persistence hooks ----
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index 9b853ee0..7437f692 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -1135,3 +1135,157 @@ def test_apigwv1_custom_id_absent_uses_random(apigw_v1):
resp = apigw_v1.create_rest_api(name="v1-random")
# _new_id() returns up to 10 hex chars; trimmed to [:8] in _create_rest_api.
assert 8 <= len(resp["id"]) <= 10
+
+
+def test_apigwv1_lambda_proxy_emits_cloudwatch_logs(apigw_v1, lam, logs):
+ """Lambda invoked via API Gateway v1 REST proxy must emit CloudWatch Logs."""
+ import urllib.request as _urlreq
+
+ fname = f"intg-v1-cwl-{_uuid_mod.uuid4().hex[:8]}"
+ marker = f"MARKER-{_uuid_mod.uuid4().hex[:8]}"
+ code = (
+ f"import sys\n"
+ f"def handler(event, context):\n"
+ f" print('{marker}')\n"
+ f" return {{'statusCode': 200, 'body': 'ok'}}\n"
+ ).encode()
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", code)
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Code={"ZipFile": buf.getvalue()},
+ )
+
+ api_id = apigw_v1.create_rest_api(name=f"v1-cwl-{fname}")["id"]
+ root = next(r for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ resource_id = apigw_v1.create_resource(
+ restApiId=api_id,
+ parentId=root["id"],
+ pathPart="cwltest",
+ )["id"]
+ apigw_v1.put_method(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ authorizationType="NONE",
+ )
+ apigw_v1.put_integration(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ type="AWS_PROXY",
+ integrationHttpMethod="POST",
+ uri=f"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:{fname}/invocations",
+ )
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="test", deploymentId=dep_id)
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/test/cwltest"
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp = _urlreq.urlopen(req)
+ assert resp.status == 200
+
+ # Verify CloudWatch Logs contain the marker text
+ log_group = f"/aws/lambda/{fname}"
+ streams = logs.describe_log_streams(logGroupName=log_group)["logStreams"]
+ assert len(streams) >= 1, f"Expected at least one log stream in {log_group}"
+
+ all_messages = []
+ for stream in streams:
+ events = logs.get_log_events(
+ logGroupName=log_group,
+ logStreamName=stream["logStreamName"],
+ )["events"]
+ all_messages.extend(e["message"] for e in events)
+
+ assert any(marker in msg for msg in all_messages), (
+ f"Marker '{marker}' not found in CloudWatch Logs. Messages: {all_messages}"
+ )
+ assert any(msg.startswith("START RequestId:") for msg in all_messages)
+ assert any(msg.startswith("END RequestId:") for msg in all_messages)
+ assert any(msg.startswith("REPORT RequestId:") for msg in all_messages)
+
+ # Cleanup
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_apigwv1_lambda_proxy_emits_cloudwatch_logs_nodejs(apigw_v1, lam, logs):
+ """Node.js Lambda invoked via API Gateway v1 REST proxy must emit CloudWatch Logs."""
+ import urllib.request as _urlreq
+
+ fname = f"intg-v1-cwl-js-{_uuid_mod.uuid4().hex[:8]}"
+ marker = f"JSMARKER-{_uuid_mod.uuid4().hex[:8]}"
+ code = (
+ "exports.handler = async (event) => {\n"
+ f" console.log('{marker}');\n"
+ " return { statusCode: 200, body: 'ok' };\n"
+ "};\n"
+ )
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.js", code)
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="nodejs20.x",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Code={"ZipFile": buf.getvalue()},
+ )
+
+ api_id = apigw_v1.create_rest_api(name=f"v1-cwl-js-{fname}")["id"]
+ root = next(r for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ resource_id = apigw_v1.create_resource(
+ restApiId=api_id,
+ parentId=root["id"],
+ pathPart="cwljs",
+ )["id"]
+ apigw_v1.put_method(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ authorizationType="NONE",
+ )
+ apigw_v1.put_integration(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ type="AWS_PROXY",
+ integrationHttpMethod="POST",
+ uri=f"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:{fname}/invocations",
+ )
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="test", deploymentId=dep_id)
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/test/cwljs"
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp = _urlreq.urlopen(req)
+ assert resp.status == 200
+
+ log_group = f"/aws/lambda/{fname}"
+ streams = logs.describe_log_streams(logGroupName=log_group)["logStreams"]
+ assert len(streams) >= 1
+
+ all_messages = []
+ for stream in streams:
+ events = logs.get_log_events(
+ logGroupName=log_group,
+ logStreamName=stream["logStreamName"],
+ )["events"]
+ all_messages.extend(e["message"] for e in events)
+
+ assert any(marker in msg for msg in all_messages), (
+ f"Marker '{marker}' not found in CloudWatch Logs. Messages: {all_messages}"
+ )
+ assert any(msg.startswith("START RequestId:") for msg in all_messages)
+ assert any(msg.startswith("END RequestId:") for msg in all_messages)
+ assert any(msg.startswith("REPORT RequestId:") for msg in all_messages)
+
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ lam.delete_function(FunctionName=fname)
diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.py
index 9129bf1f..c811fa59 100644
--- a/tests/test_apigatewayv2.py
+++ b/tests/test_apigatewayv2.py
@@ -21,6 +21,12 @@ def _make_zip(code: str) -> bytes:
zf.writestr("index.py", code)
return buf.getvalue()
+def _make_zip_js(code: str, filename: str = "index.js") -> bytes:
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr(filename, code)
+ return buf.getvalue()
+
_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"
def test_apigw_create_api(apigw):
@@ -1789,3 +1795,138 @@ def test_apigwv2_extract_lambda_ref_matrix():
name, qualifier = parse(ref)
assert name == expected_name, f"{uri!r} → name={name!r}, expected {expected_name!r}"
assert qualifier == expected_q, f"{uri!r} → qualifier={qualifier!r}, expected {expected_q!r}"
+
+
+def test_apigw_lambda_proxy_emits_cloudwatch_logs(apigw, lam, logs):
+ """Lambda invoked via API Gateway v2 proxy must emit CloudWatch Logs."""
+ import urllib.request as _urlreq
+
+ fname = f"intg-apigw-cwl-{_uuid_mod.uuid4().hex[:8]}"
+ marker = f"MARKER-{_uuid_mod.uuid4().hex[:8]}"
+ code = (
+ "import sys\n"
+ "def handler(event, context):\n"
+ f" print('{marker}')\n"
+ " return {'statusCode': 200, 'body': 'ok'}\n"
+ )
+
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(code)},
+ )
+
+ api_id = apigw.create_api(Name=f"cwl-test-{fname}", ProtocolType="HTTP")["ApiId"]
+ int_id = apigw.create_integration(
+ ApiId=api_id,
+ IntegrationType="AWS_PROXY",
+ IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{fname}",
+ PayloadFormatVersion="2.0",
+ )["IntegrationId"]
+ route_id = apigw.create_route(
+ ApiId=api_id,
+ RouteKey="GET /cwltest",
+ Target=f"integrations/{int_id}",
+ )["RouteId"]
+ apigw.create_stage(ApiId=api_id, StageName="$default")
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/$default/cwltest"
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp = _urlreq.urlopen(req)
+ assert resp.status == 200
+
+ # Verify CloudWatch Logs contain the marker text
+ log_group = f"/aws/lambda/{fname}"
+ streams = logs.describe_log_streams(logGroupName=log_group)["logStreams"]
+ assert len(streams) >= 1, f"Expected at least one log stream in {log_group}"
+
+ all_messages = []
+ for stream in streams:
+ events = logs.get_log_events(
+ logGroupName=log_group,
+ logStreamName=stream["logStreamName"],
+ )["events"]
+ all_messages.extend(e["message"] for e in events)
+
+ assert any(marker in msg for msg in all_messages), (
+ f"Marker '{marker}' not found in CloudWatch Logs. Messages: {all_messages}"
+ )
+ # Verify START/END/REPORT structure
+ assert any(msg.startswith("START RequestId:") for msg in all_messages)
+ assert any(msg.startswith("END RequestId:") for msg in all_messages)
+ assert any(msg.startswith("REPORT RequestId:") for msg in all_messages)
+
+ # Cleanup
+ apigw.delete_route(ApiId=api_id, RouteId=route_id)
+ apigw.delete_integration(ApiId=api_id, IntegrationId=int_id)
+ apigw.delete_api(ApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_apigw_lambda_proxy_emits_cloudwatch_logs_nodejs(apigw, lam, logs):
+ """Node.js Lambda invoked via API Gateway v2 proxy must emit CloudWatch Logs."""
+ import urllib.request as _urlreq
+
+ fname = f"intg-apigw-cwl-js-{_uuid_mod.uuid4().hex[:8]}"
+ marker = f"JSMARKER-{_uuid_mod.uuid4().hex[:8]}"
+ code = (
+ "exports.handler = async (event) => {\n"
+ f" console.log('{marker}');\n"
+ " return { statusCode: 200, body: 'ok' };\n"
+ "};\n"
+ )
+
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="nodejs20.x",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip_js(code)},
+ )
+
+ api_id = apigw.create_api(Name=f"cwl-js-{fname}", ProtocolType="HTTP")["ApiId"]
+ int_id = apigw.create_integration(
+ ApiId=api_id,
+ IntegrationType="AWS_PROXY",
+ IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{fname}",
+ PayloadFormatVersion="2.0",
+ )["IntegrationId"]
+ route_id = apigw.create_route(
+ ApiId=api_id,
+ RouteKey="GET /cwljs",
+ Target=f"integrations/{int_id}",
+ )["RouteId"]
+ apigw.create_stage(ApiId=api_id, StageName="$default")
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/$default/cwljs"
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp = _urlreq.urlopen(req)
+ assert resp.status == 200
+
+ log_group = f"/aws/lambda/{fname}"
+ streams = logs.describe_log_streams(logGroupName=log_group)["logStreams"]
+ assert len(streams) >= 1
+
+ all_messages = []
+ for stream in streams:
+ events = logs.get_log_events(
+ logGroupName=log_group,
+ logStreamName=stream["logStreamName"],
+ )["events"]
+ all_messages.extend(e["message"] for e in events)
+
+ assert any(marker in msg for msg in all_messages), (
+ f"Marker '{marker}' not found in CloudWatch Logs. Messages: {all_messages}"
+ )
+ assert any(msg.startswith("START RequestId:") for msg in all_messages)
+ assert any(msg.startswith("END RequestId:") for msg in all_messages)
+ assert any(msg.startswith("REPORT RequestId:") for msg in all_messages)
+
+ apigw.delete_route(ApiId=api_id, RouteId=route_id)
+ apigw.delete_integration(ApiId=api_id, IntegrationId=int_id)
+ apigw.delete_api(ApiId=api_id)
+ lam.delete_function(FunctionName=fname)
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 53f00729..2c170bb3 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -2731,3 +2731,171 @@ def test_invoke_rie_classifies_unhandled_vs_handled():
if has_header or (isinstance(parsed_error_payload, dict) and parsed_error_payload.get("errorType")):
classification = "Unhandled" if has_header else "Handled"
assert classification == "Handled"
+
+
+def test_lambda_invoke_stderr_captured_in_log_result(lam):
+ """Direct Lambda.Invoke captures print() output in X-Amz-Log-Result header."""
+ import base64
+
+ fname = f"lam-log-capture-{_uuid_mod.uuid4().hex[:8]}"
+ marker_1 = f"LINE1-{_uuid_mod.uuid4().hex[:8]}"
+ marker_2 = f"LINE2-{_uuid_mod.uuid4().hex[:8]}"
+ code = (
+ "def handler(event, context):\n"
+ f" print('{marker_1}')\n"
+ f" print('{marker_2}')\n"
+ " return {'statusCode': 200, 'body': 'ok'}\n"
+ )
+
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(code)},
+ )
+
+ try:
+ resp = lam.invoke(
+ FunctionName=fname,
+ Payload=json.dumps({}),
+ LogType="Tail",
+ )
+ assert resp["StatusCode"] == 200
+
+ log_result = resp.get("LogResult", "")
+ assert log_result, "X-Amz-Log-Result header should be non-empty"
+ decoded = base64.b64decode(log_result).decode("utf-8")
+ assert marker_1 in decoded, f"Expected '{marker_1}' in log output: {decoded}"
+ assert marker_2 in decoded, f"Expected '{marker_2}' in log output: {decoded}"
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_invoke_emits_cloudwatch_logs(lam, logs):
+ """Direct Lambda.Invoke emits START/body/END/REPORT to CloudWatch Logs."""
+ fname = f"lam-cwl-direct-{_uuid_mod.uuid4().hex[:8]}"
+ marker = f"CWL-MARKER-{_uuid_mod.uuid4().hex[:8]}"
+ code = (
+ "def handler(event, context):\n"
+ f" print('{marker}')\n"
+ " return {'statusCode': 200, 'body': 'ok'}\n"
+ )
+
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(code)},
+ )
+
+ try:
+ resp = lam.invoke(FunctionName=fname, Payload=json.dumps({}))
+ assert resp["StatusCode"] == 200
+
+ log_group = f"/aws/lambda/{fname}"
+ streams = logs.describe_log_streams(logGroupName=log_group)["logStreams"]
+ assert len(streams) >= 1
+
+ all_messages = []
+ for stream in streams:
+ events = logs.get_log_events(
+ logGroupName=log_group,
+ logStreamName=stream["logStreamName"],
+ )["events"]
+ all_messages.extend(e["message"] for e in events)
+
+ assert any(marker in msg for msg in all_messages), (
+ f"Marker '{marker}' not found in CW Logs: {all_messages}"
+ )
+ assert any(msg.startswith("START RequestId:") for msg in all_messages)
+ assert any(msg.startswith("END RequestId:") for msg in all_messages)
+ assert any(msg.startswith("REPORT RequestId:") for msg in all_messages)
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_invoke_stderr_captured_in_log_result_nodejs(lam):
+ """Node.js Lambda console.log output is captured in X-Amz-Log-Result header."""
+ import base64
+
+ fname = f"lam-log-capture-js-{_uuid_mod.uuid4().hex[:8]}"
+ marker_1 = f"JSLINE1-{_uuid_mod.uuid4().hex[:8]}"
+ marker_2 = f"JSLINE2-{_uuid_mod.uuid4().hex[:8]}"
+ code = (
+ "exports.handler = async (event) => {\n"
+ f" console.log('{marker_1}');\n"
+ f" console.log('{marker_2}');\n"
+ " return { statusCode: 200, body: 'ok' };\n"
+ "};\n"
+ )
+
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="nodejs20.x",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip_js(code)},
+ )
+
+ try:
+ resp = lam.invoke(
+ FunctionName=fname,
+ Payload=json.dumps({}),
+ LogType="Tail",
+ )
+ assert resp["StatusCode"] == 200
+
+ log_result = resp.get("LogResult", "")
+ assert log_result, "X-Amz-Log-Result header should be non-empty"
+ decoded = base64.b64decode(log_result).decode("utf-8")
+ assert marker_1 in decoded, f"Expected '{marker_1}' in log output: {decoded}"
+ assert marker_2 in decoded, f"Expected '{marker_2}' in log output: {decoded}"
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_invoke_emits_cloudwatch_logs_nodejs(lam, logs):
+ """Node.js Lambda console.log emits to CloudWatch Logs on direct invoke."""
+ fname = f"lam-cwl-direct-js-{_uuid_mod.uuid4().hex[:8]}"
+ marker = f"JSCWL-MARKER-{_uuid_mod.uuid4().hex[:8]}"
+ code = (
+ "exports.handler = async (event) => {\n"
+ f" console.log('{marker}');\n"
+ " return { statusCode: 200, body: 'ok' };\n"
+ "};\n"
+ )
+
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="nodejs20.x",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip_js(code)},
+ )
+
+ try:
+ resp = lam.invoke(FunctionName=fname, Payload=json.dumps({}))
+ assert resp["StatusCode"] == 200
+
+ log_group = f"/aws/lambda/{fname}"
+ streams = logs.describe_log_streams(logGroupName=log_group)["logStreams"]
+ assert len(streams) >= 1
+
+ all_messages = []
+ for stream in streams:
+ events = logs.get_log_events(
+ logGroupName=log_group,
+ logStreamName=stream["logStreamName"],
+ )["events"]
+ all_messages.extend(e["message"] for e in events)
+
+ assert any(marker in msg for msg in all_messages), (
+ f"Marker '{marker}' not found in CW Logs: {all_messages}"
+ )
+ assert any(msg.startswith("START RequestId:") for msg in all_messages)
+ assert any(msg.startswith("END RequestId:") for msg in all_messages)
+ assert any(msg.startswith("REPORT RequestId:") for msg in all_messages)
+ finally:
+ lam.delete_function(FunctionName=fname)