1
+ package org .apache .logging .log4j .core .layout ;
2
+
3
+ import java .io .IOException ;
4
+ import java .nio .channels .FileChannel ;
5
+ import java .nio .file .Files ;
6
+ import java .nio .file .Paths ;
7
+ import java .nio .file .StandardOpenOption ;
8
+ import java .util .Map ;
9
+ import java .util .stream .Stream ;
10
+
11
+ import com .amazonaws .services .lambda .runtime .Context ;
12
+ import com .amazonaws .services .lambda .runtime .RequestHandler ;
13
+ import com .fasterxml .jackson .core .JsonProcessingException ;
14
+ import com .fasterxml .jackson .databind .ObjectMapper ;
15
+ import org .junit .jupiter .api .BeforeEach ;
16
+ import org .junit .jupiter .api .Test ;
17
+ import org .mockito .Mock ;
18
+ import software .amazon .lambda .handlers .PowerLogToolEnabled ;
19
+
20
+ import static java .util .Collections .emptyMap ;
21
+ import static org .assertj .core .api .Assertions .assertThat ;
22
+ import static org .assertj .core .api .Assertions .fail ;
23
+ import static org .mockito .Mockito .when ;
24
+ import static org .mockito .MockitoAnnotations .initMocks ;
25
+
26
+ class LambdaJsonLayoutTest {
27
+
28
+ private RequestHandler <Object , Object > handler = new PowerLogToolEnabled ();
29
+
30
+ @ Mock
31
+ private Context context ;
32
+
33
+ @ BeforeEach
34
+ void setUp () throws IOException {
35
+ initMocks (this );
36
+ setupContext ();
37
+ //Make sure file is cleaned up before running full stack logging regression
38
+ FileChannel .open (Paths .get ("target/logfile.json" ), StandardOpenOption .WRITE ).truncate (0 ).close ();
39
+ }
40
+
41
+ @ Test
42
+ void shouldLogInStructuredFormat () throws IOException {
43
+ handler .handleRequest ("test" , context );
44
+
45
+ assertThat (Files .lines (Paths .get ("target/logfile.json" )))
46
+ .hasSize (1 )
47
+ .allSatisfy (line -> assertThat (parseToMap (line ))
48
+ .containsEntry ("functionName" , "testFunction" )
49
+ .containsEntry ("functionVersion" , "1" )
50
+ .containsEntry ("functionMemorySize" , "10" )
51
+ .containsEntry ("functionArn" , "testArn" )
52
+ .containsKey ("timestamp" )
53
+ .containsKey ("message" )
54
+ .containsKey ("service" ));
55
+ }
56
+
57
+ private Map <String , Object > parseToMap (String stringAsJson ) {
58
+ try {
59
+ return new ObjectMapper ().readValue (stringAsJson , Map .class );
60
+ } catch (JsonProcessingException e ) {
61
+ fail ("Failed parsing logger line " + stringAsJson );
62
+ return emptyMap ();
63
+ }
64
+ }
65
+
66
+ private void setupContext () {
67
+ when (context .getFunctionName ()).thenReturn ("testFunction" );
68
+ when (context .getInvokedFunctionArn ()).thenReturn ("testArn" );
69
+ when (context .getFunctionVersion ()).thenReturn ("1" );
70
+ when (context .getMemoryLimitInMB ()).thenReturn (10 );
71
+ }
72
+ }
0 commit comments