From cb85fdd782f6579a3b5ca1bd5df8e742fa2d8da7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Stormacq?= Date: Tue, 22 Jul 2025 07:31:00 +0200 Subject: [PATCH] fix [core] trace level shows the first kb of the payload before being decoded (#534) Add a log statement in the Lambda loop, before calling the user's handler to show the raw payload before any attempt to decode it. This was available in Runtime v1 and is now ported to v2. This fixes https://github.com/swift-server/swift-aws-lambda-runtime/issues/404 ### Motivation: This is useful when handling custom event and there is a Decoding error. It allows to see the exact payload received by the handler before any attempt to decode it. ### Modifications: Add a log.trace statement with metatadata. Metadata are computed only when the log level is trace or below. ### Result: ``` 2025-07-21T08:58:33+0200 trace LambdaRuntime : Event's first bytes={"name": "me", "age": 50} aws-request-id=769127502334125 [AWSLambdaRuntime] sending invocation event to lambda handler ``` --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- Sources/AWSLambdaRuntime/Lambda.swift | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Sources/AWSLambdaRuntime/Lambda.swift b/Sources/AWSLambdaRuntime/Lambda.swift index e38851c0..5412c139 100644 --- a/Sources/AWSLambdaRuntime/Lambda.swift +++ b/Sources/AWSLambdaRuntime/Lambda.swift @@ -44,6 +44,24 @@ public enum Lambda { let (invocation, writer) = try await runtimeClient.nextInvocation() logger[metadataKey: "aws-request-id"] = "\(invocation.metadata.requestID)" + // when log level is trace or lower, print the first Kb of the payload + let bytes = invocation.event + let maxPayloadPreviewSize = 1024 + var metadata: Logger.Metadata? = nil + if logger.logLevel <= .trace, + let buffer = bytes.getSlice(at: 0, length: min(bytes.readableBytes, maxPayloadPreviewSize)) + { + metadata = [ + "Event's first bytes": .string( + String(buffer: buffer) + (bytes.readableBytes > maxPayloadPreviewSize ? "..." : "") + ) + ] + } + logger.trace( + "Sending invocation event to lambda handler", + metadata: metadata + ) + do { try await handler.handle( invocation.event,