Skip to content

Commit 3fa987a

Browse files
committed
load env var at init
1 parent 6084cdd commit 3fa987a

File tree

2 files changed

+83
-38
lines changed

2 files changed

+83
-38
lines changed

powertools-logging/src/main/java/software/amazon/lambda/powertools/logging/internal/LambdaLoggingAspect.java

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,6 @@
5656
import org.slf4j.LoggerFactory;
5757
import org.slf4j.MDC;
5858
import org.slf4j.event.Level;
59-
import software.amazon.lambda.powertools.common.internal.SystemWrapper;
6059
import software.amazon.lambda.powertools.logging.Logging;
6160
import software.amazon.lambda.powertools.logging.LoggingUtils;
6261
import software.amazon.lambda.powertools.utilities.JsonConfig;
@@ -69,6 +68,9 @@ public final class LambdaLoggingAspect {
6968
private static final Random SAMPLER = new Random();
7069
private static final String LOG_LEVEL = System.getenv("POWERTOOLS_LOG_LEVEL");
7170
private static final LoggingManager loggingManager;
71+
72+
private static String LOG_EVENT = System.getenv("POWERTOOLS_LOGGER_LOG_EVENT"); /* not final for test purpose */
73+
private static String SAMPLING_RATE = System.getenv("POWERTOOLS_LOGGER_SAMPLE_RATE"); /* not final for test purpose */
7274
private static Level LEVEL_AT_INITIALISATION; /* not final for test purpose */
7375

7476
static {
@@ -187,7 +189,7 @@ public Object around(ProceedingJoinPoint pjp,
187189

188190
getXrayTraceId().ifPresent(xRayTraceId -> appendKey(FUNCTION_TRACE_ID.getName(), xRayTraceId));
189191

190-
if (logging.logEvent() || "true".equals(SystemWrapper.getenv("POWERTOOLS_LOGGER_LOG_EVENT"))) {
192+
if (logging.logEvent() || "true".equals(LOG_EVENT)) {
191193
proceedArgs = logEvent(pjp);
192194
}
193195

@@ -237,7 +239,7 @@ private void setLogLevelBasedOnSamplingRate(final ProceedingJoinPoint pjp,
237239
}
238240

239241
private double samplingRate(final Logging logging) {
240-
String sampleRate = SystemWrapper.getenv("POWERTOOLS_LOGGER_SAMPLE_RATE");
242+
String sampleRate = SAMPLING_RATE;
241243
if (null != sampleRate) {
242244
try {
243245
return Double.parseDouble(sampleRate);

powertools-logging/src/test/java/software/amazon/lambda/powertools/logging/internal/LambdaLoggingAspectTest.java

Lines changed: 78 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,8 @@ void setUp() throws IllegalAccessException, NoSuchMethodException, InvocationTar
9393
requestHandler = new PowertoolsLogEnabled();
9494
requestStreamHandler = new PowertoolsLogEnabledForStream();
9595
resetLogLevel(Level.INFO);
96+
writeStaticField(LambdaLoggingAspect.class, "LOG_EVENT", null, true);
97+
writeStaticField(LambdaLoggingAspect.class, "SAMPLING_RATE", null, true);
9698
try {
9799
FileChannel.open(Paths.get("target/logfile.json"), StandardOpenOption.WRITE).truncate(0).close();
98100
} catch (NoSuchFileException e) {
@@ -186,58 +188,66 @@ void shouldClearStateWhenClearStateIsTrue() {
186188
@Test
187189
void shouldLogDebugWhenSamplingEqualsOne() {
188190
PowertoolsLogSamplingEnabled handler = new PowertoolsLogSamplingEnabled();
191+
189192
Boolean debugEnabled = handler.handleRequest(new Object(), context);
193+
190194
assertThat(debugEnabled).isTrue();
191195
}
192196

193197
@Test
194-
void shouldLogDebugWhenSamplingEnvVarEqualsOne() {
195-
try (MockedStatic<SystemWrapper> mocked = mockStatic(SystemWrapper.class)) {
196-
mocked.when(() -> getenv("POWERTOOLS_LOGGER_SAMPLE_RATE"))
197-
.thenReturn("1");
198+
void shouldLogDebugWhenSamplingEnvVarEqualsOne() throws IllegalAccessException {
199+
// GIVEN
200+
writeStaticField(LambdaLoggingAspect.class, "SAMPLING_RATE", "1", true);
201+
PowertoolsLogEnabled handler = new PowertoolsLogEnabled();
198202

199-
PowertoolsLogEnabled handler = new PowertoolsLogEnabled();
200-
handler.handleRequest(new Object(), context);
201-
File logFile = new File("target/logfile.json");
202-
assertThat(contentOf(logFile)).contains("Test debug event");
203-
}
203+
// WHEN
204+
handler.handleRequest(new Object(), context);
205+
206+
// THEN
207+
File logFile = new File("target/logfile.json");
208+
assertThat(contentOf(logFile)).contains("Test debug event");
204209
}
205210

206211
@Test
207-
void shouldNotLogDebugWhenSamplingEnvVarIsTooBig() {
208-
try (MockedStatic<SystemWrapper> mocked = mockStatic(SystemWrapper.class)) {
209-
mocked.when(() -> getenv("POWERTOOLS_LOGGER_SAMPLE_RATE"))
210-
.thenReturn("42");
212+
void shouldNotLogDebugWhenSamplingEnvVarIsTooBig() throws IllegalAccessException {
213+
// GIVEN
214+
writeStaticField(LambdaLoggingAspect.class, "SAMPLING_RATE", "42", true);
211215

212-
requestHandler.handleRequest(new Object(), context);
213-
File logFile = new File("target/logfile.json");
214-
assertThat(contentOf(logFile)).doesNotContain("Test debug event");
215-
}
216+
// WHEN
217+
requestHandler.handleRequest(new Object(), context);
218+
219+
// THEN
220+
File logFile = new File("target/logfile.json");
221+
assertThat(contentOf(logFile)).doesNotContain("Test debug event");
216222
}
217223

218224
@Test
219-
void shouldNotLogDebugWhenSamplingEnvVarIsInvalid() {
220-
try (MockedStatic<SystemWrapper> mocked = mockStatic(SystemWrapper.class)) {
221-
mocked.when(() -> getenv("POWERTOOLS_LOGGER_SAMPLE_RATE"))
222-
.thenReturn("NotANumber");
225+
void shouldNotLogDebugWhenSamplingEnvVarIsInvalid() throws IllegalAccessException {
226+
// GIVEN
227+
writeStaticField(LambdaLoggingAspect.class, "SAMPLING_RATE", "NotANumber", true);
223228

229+
// WHEN
224230
requestHandler.handleRequest(new Object(), context);
225-
File logFile = new File("target/logfile.json");
226-
assertThat(contentOf(logFile)).doesNotContain("Test debug event");
227-
assertThat(contentOf(logFile)).contains(
228-
"Skipping sampling rate on environment variable configuration because of invalid value");
229-
}
231+
232+
// THEN
233+
File logFile = new File("target/logfile.json");
234+
assertThat(contentOf(logFile)).doesNotContain("Test debug event");
235+
assertThat(contentOf(logFile)).contains(
236+
"Skipping sampling rate on environment variable configuration because of invalid value");
230237
}
231238

232239
@Test
233240
void shouldNotLogDebugWhenSamplingEqualsZero() {
234241
PowertoolsLogSamplingDisabled handler = new PowertoolsLogSamplingDisabled();
242+
235243
Boolean debugEnabled = handler.handleRequest(new Object(), context);
244+
236245
assertThat(debugEnabled).isFalse();
237246
}
238247

239248
@Test
240249
void shouldHaveNoEffectIfNotUsedOnLambdaHandler() {
250+
// GIVEN
241251
PowertoolsLogEnabled handler = new PowertoolsLogEnabled();
242252

243253
handler.anotherMethod();
@@ -247,24 +257,31 @@ void shouldHaveNoEffectIfNotUsedOnLambdaHandler() {
247257

248258
@Test
249259
void shouldLogServiceNameWhenEnvVarSet() throws IllegalAccessException {
260+
// GIVEN
250261
writeStaticField(LambdaHandlerProcessor.class, "SERVICE_NAME", "testService", true);
262+
263+
// WHEN
251264
requestHandler.handleRequest(new Object(), context);
252265

266+
// THEN
253267
assertThat(MDC.getCopyOfContextMap())
254268
.hasSize(EXPECTED_CONTEXT_SIZE)
255269
.containsEntry(SERVICE.getName(), "testService");
256270
}
257271

258272
@Test
259273
void shouldLogxRayTraceIdEnvVarSet() {
274+
// GIVEN
260275
String xRayTraceId = "1-5759e988-bd862e3fe1be46a994272793";
261276

262277
try (MockedStatic<SystemWrapper> mocked = mockStatic(SystemWrapper.class)) {
263278
mocked.when(() -> getenv("_X_AMZN_TRACE_ID"))
264279
.thenReturn("Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1\"");
265280

281+
// WHEN
266282
requestHandler.handleRequest(new Object(), context);
267283

284+
// THEN
268285
assertThat(MDC.getCopyOfContextMap())
269286
.hasSize(EXPECTED_CONTEXT_SIZE + 1)
270287
.containsEntry(FUNCTION_TRACE_ID.getName(), xRayTraceId);
@@ -273,35 +290,41 @@ void shouldLogxRayTraceIdEnvVarSet() {
273290

274291
@Test
275292
void shouldLogEventForHandlerWithLogEventAnnotation() {
293+
// GIVEN
276294
requestHandler = new PowertoolsLogEvent();
277295

296+
// WHEN
278297
requestHandler.handleRequest(Collections.singletonList("ListOfOneElement"), context);
279298

299+
// THEN
280300
File logFile = new File("target/logfile.json");
281301
assertThat(contentOf(logFile)).contains("[\"ListOfOneElement\"]");
282302
}
283303

284304
@Test
285-
void shouldLogEventForHandlerWithLogEventEnvVar() {
305+
void shouldLogEventForHandlerWithLogEventEnvVar() throws IllegalAccessException {
306+
// GIVEN
307+
writeStaticField(LambdaLoggingAspect.class, "LOG_EVENT", "true", true);
286308
requestHandler = new PowertoolsLogEnabled();
287309

288-
try (MockedStatic<SystemWrapper> mocked = mockStatic(SystemWrapper.class)) {
289-
mocked.when(() -> getenv("POWERTOOLS_LOGGER_LOG_EVENT"))
290-
.thenReturn("true");
291-
292-
requestHandler.handleRequest(Collections.singletonList("ListOfOneElement"), context);
310+
// WHEN
311+
requestHandler.handleRequest(Collections.singletonList("ListOfOneElement"), context);
293312

294-
File logFile = new File("target/logfile.json");
295-
assertThat(contentOf(logFile)).contains("[\"ListOfOneElement\"]");
296-
}
313+
// THEN
314+
File logFile = new File("target/logfile.json");
315+
assertThat(contentOf(logFile)).contains("[\"ListOfOneElement\"]");
297316
}
298317

299318
@Test
300319
void shouldLogEventForStreamHandler() throws IOException {
320+
// GIVEN
301321
requestStreamHandler = new PowertoolsLogEventForStream();
302322
ByteArrayOutputStream output = new ByteArrayOutputStream();
323+
324+
// WHEN
303325
requestStreamHandler.handleRequest(new ByteArrayInputStream(new ObjectMapper().writeValueAsBytes(Collections.singletonMap("key", "value"))), output, context);
304326

327+
// THEN
305328
assertThat(new String(output.toByteArray(), StandardCharsets.UTF_8))
306329
.isNotEmpty();
307330

@@ -312,9 +335,13 @@ void shouldLogEventForStreamHandler() throws IOException {
312335
@ParameterizedTest
313336
@Event(value = "apiGatewayProxyEventV1.json", type = APIGatewayProxyRequestEvent.class)
314337
void shouldLogCorrelationIdOnAPIGatewayProxyRequestEvent(APIGatewayProxyRequestEvent event) {
338+
// GIVEN
315339
RequestHandler<APIGatewayProxyRequestEvent, Object> handler = new PowertoolsLogApiGatewayRestApiCorrelationId();
340+
341+
// WHEN
316342
handler.handleRequest(event, context);
317343

344+
// THEN
318345
assertThat(MDC.getCopyOfContextMap())
319346
.hasSize(EXPECTED_CONTEXT_SIZE + 1)
320347
.containsEntry("correlation_id", event.getRequestContext().getRequestId());
@@ -323,9 +350,13 @@ void shouldLogCorrelationIdOnAPIGatewayProxyRequestEvent(APIGatewayProxyRequestE
323350
@ParameterizedTest
324351
@Event(value = "apiGatewayProxyEventV2.json", type = APIGatewayV2HTTPEvent.class)
325352
void shouldLogCorrelationIdOnAPIGatewayV2HTTPEvent(APIGatewayV2HTTPEvent event) {
353+
// GIVEN
326354
RequestHandler<APIGatewayV2HTTPEvent, Object> handler = new PowertoolsLogApiGatewayHttpApiCorrelationId();
355+
356+
// WHEN
327357
handler.handleRequest(event, context);
328358

359+
// THEN
329360
assertThat(MDC.getCopyOfContextMap())
330361
.hasSize(EXPECTED_CONTEXT_SIZE + 1)
331362
.containsEntry("correlation_id", event.getRequestContext().getRequestId());
@@ -334,35 +365,47 @@ void shouldLogCorrelationIdOnAPIGatewayV2HTTPEvent(APIGatewayV2HTTPEvent event)
334365
@ParameterizedTest
335366
@Event(value = "albEvent.json", type = ApplicationLoadBalancerRequestEvent.class)
336367
void shouldLogCorrelationIdOnALBEvent(ApplicationLoadBalancerRequestEvent event) {
368+
// GIVEN
337369
RequestHandler<ApplicationLoadBalancerRequestEvent, Object> handler = new PowertoolsLogAlbCorrelationId();
370+
371+
// WHEN
338372
handler.handleRequest(event, context);
339373

374+
// THEN
340375
assertThat(MDC.getCopyOfContextMap())
341376
.hasSize(EXPECTED_CONTEXT_SIZE + 1)
342377
.containsEntry("correlation_id", event.getHeaders().get("x-amzn-trace-id"));
343378
}
344379

345380
@Test
346381
void shouldLogCorrelationIdOnStreamHandler() throws IOException {
382+
// GIVEN
347383
RequestStreamHandler handler = new PowertoolsLogEventBridgeCorrelationId();
348384
String eventId = "3";
349385
String event = "{\"id\":" + eventId + "}"; // CorrelationIdPath.EVENT_BRIDGE
350386
ByteArrayInputStream inputStream = new ByteArrayInputStream(event.getBytes());
387+
388+
// WHEN
351389
handler.handleRequest(inputStream, new ByteArrayOutputStream(), context);
352390

391+
// THEN
353392
assertThat(MDC.getCopyOfContextMap())
354393
.hasSize(EXPECTED_CONTEXT_SIZE + 1)
355394
.containsEntry("correlation_id", eventId);
356395
}
357396

358397
@Test
359398
void shouldLogCorrelationIdOnAppSyncEvent() throws IOException {
399+
// GIVEN
360400
RequestStreamHandler handler = new PowertoolsLogAppSyncCorrelationId();
361401
String eventId = "456";
362402
String event = "{\"request\":{\"headers\":{\"x-amzn-trace-id\":" + eventId + "}}}"; // CorrelationIdPath.APPSYNC_RESOLVER
363403
ByteArrayInputStream inputStream = new ByteArrayInputStream(event.getBytes());
404+
405+
// WHEN
364406
handler.handleRequest(inputStream, new ByteArrayOutputStream(), context);
365407

408+
// THEN
366409
assertThat(MDC.getCopyOfContextMap())
367410
.hasSize(EXPECTED_CONTEXT_SIZE + 1)
368411
.containsEntry("correlation_id", eventId);

0 commit comments

Comments
 (0)