-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
LogCaptorShould.java
735 lines (577 loc) · 27.8 KB
/
LogCaptorShould.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
/*
* Copyright 2019 Thunderberry.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.altindag.log;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.filter.LevelFilter;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.spi.FilterReply;
import nl.altindag.console.ConsoleCaptor;
import nl.altindag.log.appender.InMemoryAppender;
import nl.altindag.log.exception.LogCaptorException;
import nl.altindag.log.model.LogEvent;
import nl.altindag.log.service.LogMessage;
import nl.altindag.log.service.Service;
import nl.altindag.log.service.apache.ServiceWithApacheLog4j;
import nl.altindag.log.service.apache.ServiceWithApacheLog4jAndMdcHeaders;
import nl.altindag.log.service.apache.ServiceWithNestedApacheLog4j;
import nl.altindag.log.service.jdk.ServiceWithJavaUtilLogging;
import nl.altindag.log.service.jdk.ServiceWithNestedJavaUtilLogging;
import nl.altindag.log.service.lombok.ServiceWithLombokAndJavaUtilLogging;
import nl.altindag.log.service.lombok.ServiceWithLombokAndLog4j;
import nl.altindag.log.service.lombok.ServiceWithLombokAndLog4j2;
import nl.altindag.log.service.lombok.ServiceWithLombokAndNestedJavaUtilLogging;
import nl.altindag.log.service.lombok.ServiceWithLombokAndNestedLog4j;
import nl.altindag.log.service.lombok.ServiceWithLombokAndNestedLog4j2;
import nl.altindag.log.service.lombok.ServiceWithLombokAndSlf4j;
import nl.altindag.log.service.slfj4.ServiceWithNestedSlf4j;
import nl.altindag.log.service.slfj4.ServiceWithSlf4j;
import nl.altindag.log.service.slfj4.ServiceWithSlf4jAndCustomException;
import nl.altindag.log.service.slfj4.ServiceWithSlf4jAndMdcHeaders;
import nl.altindag.log.service.slfj4.ServiceWithSlf4jWhileUsingKeyValuePairs;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.LoggerFactory;
import org.slf4j.simple.SimpleLogger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
/**
* @author Hakan Altindag
*/
@ExtendWith(MockitoExtension.class)
class LogCaptorShould {
private LogCaptor logCaptor;
@AfterEach
void resetProperties() {
Optional.ofNullable(logCaptor)
.ifPresent(LogCaptor::resetLogLevel);
}
@Test
void captureLoggingEventsWhereApacheLogManagerIsUsed() {
logCaptor = LogCaptor.forClass(ServiceWithApacheLog4j.class);
logCaptor.setLogLevelToTrace();
Service service = new ServiceWithApacheLog4j();
service.sayHello();
assertThat(logCaptor.getInfoLogs()).containsExactly(LogMessage.INFO.getMessage());
assertThat(logCaptor.getDebugLogs()).containsExactly(LogMessage.DEBUG.getMessage());
assertThat(logCaptor.getWarnLogs()).containsExactly(LogMessage.WARN.getMessage());
assertThat(logCaptor.getErrorLogs()).containsExactly(LogMessage.ERROR.getMessage());
assertThat(logCaptor.getTraceLogs()).containsExactly(LogMessage.TRACE.getMessage());
assertThat(logCaptor.getLogs())
.hasSize(5)
.containsExactly(
LogMessage.INFO.getMessage(),
LogMessage.WARN.getMessage(),
LogMessage.ERROR.getMessage(),
LogMessage.TRACE.getMessage(),
LogMessage.DEBUG.getMessage()
);
}
@Test
void captureNestedLogsWhereApacheLogManagerIsUsed() {
logCaptor = LogCaptor.forName(ServiceWithNestedApacheLog4j.NestedService.class.getCanonicalName());
Service service = new ServiceWithNestedApacheLog4j.NestedService();
service.sayHello();
assertThat(logCaptor.getLogs()).containsExactly(LogMessage.INFO.getMessage());
}
@Test
void captureNestedLogsWhereSlf4jIsUsedWith() {
logCaptor = LogCaptor.forClass(ServiceWithNestedSlf4j.NestedService.class);
Service service = new ServiceWithNestedSlf4j.NestedService();
service.sayHello();
assertThat(logCaptor.getLogs()).containsExactly(LogMessage.INFO.getMessage());
}
@Test
void captureNestedLogsWhereJulIsUsedWith() {
logCaptor = LogCaptor.forClass(ServiceWithNestedJavaUtilLogging.NestedService.class);
Service service = new ServiceWithNestedJavaUtilLogging.NestedService();
service.sayHello();
assertThat(logCaptor.getLogs()).containsExactly(LogMessage.INFO.getMessage());
}
@Test
void captureNestedLogsWhereLombokWithJulIsUsedWith() {
logCaptor = LogCaptor.forClass(ServiceWithLombokAndNestedJavaUtilLogging.NestedService.class);
Service service = new ServiceWithLombokAndNestedJavaUtilLogging.NestedService();
service.sayHello();
assertThat(logCaptor.getLogs()).containsExactly(LogMessage.INFO.getMessage());
}
@Test
void captureNestedLogsWhereLombokWithLog4j2IsUsedWith() {
logCaptor = LogCaptor.forName(ServiceWithLombokAndNestedLog4j2.NestedService.class.getCanonicalName());
Service service = new ServiceWithLombokAndNestedLog4j2.NestedService();
service.sayHello();
assertThat(logCaptor.getLogs()).containsExactly(LogMessage.INFO.getMessage());
}
@Test
void captureNestedLogsWhereLombokWithLog4jIsUsedWith() {
logCaptor = LogCaptor.forClass(ServiceWithLombokAndNestedLog4j.NestedService.class);
Service service = new ServiceWithLombokAndNestedLog4j.NestedService();
service.sayHello();
assertThat(logCaptor.getLogs()).containsExactly(LogMessage.INFO.getMessage());
}
@Test
void captureNestedLogsWhereLombokWithSlf4jIsUsedWith() {
logCaptor = LogCaptor.forClass(ServiceWithLombokAndNestedLog4j.NestedService.class);
Service service = new ServiceWithLombokAndNestedLog4j.NestedService();
service.sayHello();
assertThat(logCaptor.getLogs()).containsExactly(LogMessage.INFO.getMessage());
}
@Test
void captureLoggingEventsWithoutSpecifyingClass() {
logCaptor = LogCaptor.forRoot();
logCaptor.setLogLevelToTrace();
Service service = new ServiceWithApacheLog4j();
service.sayHello();
assertThat(logCaptor.getInfoLogs()).containsExactly(LogMessage.INFO.getMessage());
assertThat(logCaptor.getDebugLogs()).containsExactly(LogMessage.DEBUG.getMessage());
assertThat(logCaptor.getWarnLogs()).containsExactly(LogMessage.WARN.getMessage());
assertThat(logCaptor.getErrorLogs()).containsExactly(LogMessage.ERROR.getMessage());
assertThat(logCaptor.getTraceLogs()).containsExactly(LogMessage.TRACE.getMessage());
}
@Test
void captureLoggingEventsContainingException() {
logCaptor = LogCaptor.forClass(ServiceWithSlf4jAndCustomException.class);
Service service = new ServiceWithSlf4jAndCustomException();
service.sayHello();
List<LogEvent> logEvents = logCaptor.getLogEvents();
assertThat(logEvents).hasSize(1);
LogEvent logEvent = logEvents.get(0);
assertThat(logEvent.getFormattedMessage()).isEqualTo("Caught unexpected exception");
assertThat(logEvent.getLevel()).isEqualTo("ERROR");
assertThat(logEvent.getThrowable()).isPresent();
assertThat(logEvent.getThrowable().get())
.hasMessage("KABOOM!")
.isInstanceOf(IOException.class);
}
@Test
void captureLoggingEventsContainingArguments() {
logCaptor = LogCaptor.forClass(ServiceWithSlf4j.class);
Service service = new ServiceWithSlf4j();
service.sayHello();
List<LogEvent> logEvents = logCaptor.getLogEvents();
assertThat(logEvents).hasSize(1);
LogEvent logEvent = logEvents.get(0);
assertThat(logEvent.getArguments()).contains("Enter");
assertThat(logEvent.getMessage()).isEqualTo("Keyboard not responding. Press {} key to continue...");
assertThat(logEvent.getFormattedMessage()).isEqualTo("Keyboard not responding. Press Enter key to continue...");
}
@Test
void captureLoggingEventsContainingThreadName() {
logCaptor = LogCaptor.forClass(ServiceWithSlf4j.class);
Service service = new ServiceWithSlf4j();
service.sayHello();
List<LogEvent> logEvents = logCaptor.getLogEvents();
assertThat(logEvents).hasSize(1);
LogEvent logEvent = logEvents.get(0);
assertThat(logEvent.getThreadName()).isEqualTo("main");
}
@Test
void captureLoggingEventsByUsingForNameMethodWithLogCaptor() {
logCaptor = LogCaptor.forName("nl.altindag.log.service.apache.ServiceWithApacheLog4j");
logCaptor.setLogLevelToTrace();
Service service = new ServiceWithApacheLog4j();
service.sayHello();
assertThat(logCaptor.getInfoLogs()).containsExactly(LogMessage.INFO.getMessage());
assertThat(logCaptor.getDebugLogs()).containsExactly(LogMessage.DEBUG.getMessage());
assertThat(logCaptor.getWarnLogs()).containsExactly(LogMessage.WARN.getMessage());
assertThat(logCaptor.getErrorLogs()).containsExactly(LogMessage.ERROR.getMessage());
assertThat(logCaptor.getTraceLogs()).containsExactly(LogMessage.TRACE.getMessage());
assertThat(logCaptor.getLogs())
.hasSize(5)
.containsExactly(
LogMessage.INFO.getMessage(),
LogMessage.WARN.getMessage(),
LogMessage.ERROR.getMessage(),
LogMessage.TRACE.getMessage(),
LogMessage.DEBUG.getMessage()
);
}
@Test
void captureLoggingEventsWithDebugEnabled() {
logCaptor = LogCaptor.forClass(ServiceWithApacheLog4j.class);
logCaptor.setLogLevelToInfo();
Service service = new ServiceWithApacheLog4j();
service.sayHello();
assertThat(logCaptor.getLogs())
.hasSize(3)
.containsExactly(
LogMessage.INFO.getMessage(),
LogMessage.WARN.getMessage(),
LogMessage.ERROR.getMessage()
);
logCaptor.clearLogs();
logCaptor.setLogLevelToDebug();
service.sayHello();
assertThat(logCaptor.getLogs())
.hasSize(4)
.containsExactly(
LogMessage.INFO.getMessage(),
LogMessage.WARN.getMessage(),
LogMessage.ERROR.getMessage(),
LogMessage.DEBUG.getMessage()
);
}
@Test
void captureLoggingEventsWhereLombokLog4j2IsUsed() {
logCaptor = LogCaptor.forClass(ServiceWithLombokAndLog4j2.class);
Service service = new ServiceWithLombokAndLog4j2();
service.sayHello();
assertLogMessages(logCaptor, LogMessage.INFO, LogMessage.WARN, LogMessage.DEBUG);
}
@Test
void captureLoggingEventsWithLogLevelInfoWhereLombokLog4j2IsUsed() {
logCaptor = LogCaptor.forClass(ServiceWithLombokAndLog4j2.class);
logCaptor.setLogLevelToInfo();
Service service = new ServiceWithLombokAndLog4j2();
service.sayHello();
assertLogMessages(logCaptor, LogMessage.INFO, LogMessage.WARN);
}
@Test
void captureLoggingEventsWhereLombokSlf4jIsUsed() {
logCaptor = LogCaptor.forClass(ServiceWithLombokAndSlf4j.class);
Service service = new ServiceWithLombokAndSlf4j();
service.sayHello();
assertLogMessages(logCaptor, LogMessage.INFO, LogMessage.WARN, LogMessage.DEBUG);
}
@Test
void captureLoggingEventsWithLogLevelInfoWhereLombokSlf4jIsUsed() {
logCaptor = LogCaptor.forClass(ServiceWithLombokAndSlf4j.class);
logCaptor.setLogLevelToInfo();
Service service = new ServiceWithLombokAndSlf4j();
service.sayHello();
assertLogMessages(logCaptor, LogMessage.INFO, LogMessage.WARN);
}
@Test
void captureLoggingEventsWhereLombokLog4jIsUsed() {
logCaptor = LogCaptor.forClass(ServiceWithLombokAndLog4j.class);
Service service = new ServiceWithLombokAndLog4j();
service.sayHello();
assertLogMessages(logCaptor, LogMessage.INFO, LogMessage.WARN, LogMessage.DEBUG);
}
@Test
void captureLoggingEventsWithLogLevelInfoWhereLombokLog4jIsUsed() {
logCaptor = LogCaptor.forClass(ServiceWithLombokAndLog4j.class);
logCaptor.setLogLevelToInfo();
Service service = new ServiceWithLombokAndLog4j();
service.sayHello();
assertLogMessages(logCaptor, LogMessage.INFO, LogMessage.WARN);
}
@Test
void captureLoggingEventsWhereLombokJavaUtilLoggingIsUsed() {
logCaptor = LogCaptor.forClass(ServiceWithLombokAndJavaUtilLogging.class);
Service service = new ServiceWithLombokAndJavaUtilLogging();
service.sayHello();
assertLogMessages(logCaptor, LogMessage.INFO, LogMessage.WARN);
}
@Test
void captureLoggingEventsWhereJavaUtilLoggingIsUsed() {
logCaptor = LogCaptor.forClass(ServiceWithJavaUtilLogging.class);
logCaptor.setLogLevelToTrace();
Service service = new ServiceWithJavaUtilLogging();
service.sayHello();
assertLogMessages(logCaptor, LogMessage.INFO, LogMessage.ERROR, LogMessage.DEBUG, LogMessage.TRACE);
}
@Test
void doNotCaptureLogMessagesWhenItIsDisabled() {
logCaptor = LogCaptor.forClass(ServiceWithApacheLog4j.class);
logCaptor.disableLogs();
Service service = new ServiceWithApacheLog4j();
service.sayHello();
assertThat(logCaptor.getLogs()).isEmpty();
}
@Test
void captureTimeStampOfLogsAndRetainOrderOfOccurrence() {
logCaptor = LogCaptor.forClass(ServiceWithApacheLog4j.class);
logCaptor.setLogLevelToTrace();
Service service = new ServiceWithApacheLog4j();
service.sayHello();
List<LogEvent> logEvents = logCaptor.getLogEvents();
Optional<LogEvent> infoLog = logEvents.stream().filter(logEvent -> logEvent.getLevel().equalsIgnoreCase("info")).findFirst();
Optional<LogEvent> traceLog = logEvents.stream().filter(logEvent -> logEvent.getLevel().equalsIgnoreCase("trace")).findFirst();
assertThat(infoLog).isPresent();
assertThat(traceLog).isPresent();
assertThat(infoLog.get().getTimeStamp()).isBeforeOrEqualTo(traceLog.get().getTimeStamp());
}
@Test
void captureLoggerName() {
logCaptor = LogCaptor.forRoot();
Service service = new ServiceWithApacheLog4j();
service.sayHello();
List<LogEvent> logEvents = logCaptor.getLogEvents();
assertThat(logEvents).hasSize(4);
assertThat(logEvents.get(0).getLoggerName()).isEqualTo(ServiceWithApacheLog4j.class.getName());
}
@Test
void throwExceptionWhenLoggerImplementationIsNull() {
try (MockedStatic<LoggerFactory> loggerFactoryMockedStatic = mockStatic(LoggerFactory.class)) {
loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(anyString())).thenReturn(null);
assertThatThrownBy(LogCaptor::forRoot)
.isInstanceOf(LogCaptorException.class)
.hasMessage("SLF4J Logger implementation should be of the type [ch.qos.logback.classic.Logger] but found [nothing].");
}
}
@Test
void throwExceptionWhenLoggerImplementationIsNotLogback() {
try (MockedStatic<LoggerFactory> loggerFactoryMockedStatic = mockStatic(LoggerFactory.class)) {
org.slf4j.Logger logger = mock(SimpleLogger.class);
loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(anyString())).thenReturn(logger);
assertThatThrownBy(LogCaptor::forRoot)
.isInstanceOf(LogCaptorException.class)
.hasMessage("SLF4J Logger implementation should be of the type [ch.qos.logback.classic.Logger] but found [org.slf4j.simple.SimpleLogger].");
}
}
@Test
void throwExceptionWhenLoggerImplementationIsFromAnotherClassloader() throws InvocationTargetException, InstantiationException, IllegalAccessException {
CustomClassLoader classLoader = new CustomClassLoader();
Class<?> loggerClass = classLoader.findClass("ch.qos.logback.classic.Logger");
Constructor<?> loggerConstructor = loggerClass.getDeclaredConstructors()[0];
loggerConstructor.setAccessible(true);
Object logger = loggerConstructor.newInstance(null, null, null);
try (MockedStatic<LoggerFactory> loggerFactoryMockedStatic = mockStatic(LoggerFactory.class)) {
loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(anyString())).thenReturn(logger);
assertThatThrownBy(LogCaptor::forRoot)
.isInstanceOf(LogCaptorException.class)
.hasMessage(String.format("Multiple classloaders are being used. The Logging API is created by the following classloader: [nl.altindag.log.LogCaptorShould$CustomClassLoader], " +
"while it should have been created by the following classloader: [%s].", this.getClass().getClassLoader().getClass().getName()
));
}
}
@Test
void filterInfoMessages() {
LevelFilter levelFilter = new LevelFilter();
levelFilter.setOnMismatch(FilterReply.DENY);
levelFilter.setLevel(Level.INFO);
logCaptor = LogCaptor.forClass(ServiceWithApacheLog4j.class);
logCaptor.addFilter(levelFilter);
logCaptor.setLogLevelToTrace();
Service service = new ServiceWithApacheLog4j();
service.sayHello();
assertThat(logCaptor.getLogEvents())
.extracting(LogEvent::getLevel)
.map(Level::toLevel)
.allMatch(Level.INFO::equals, "INFO");
}
@Test
void captureMdcHeadersWhereLog4jIsUsed() {
logCaptor = LogCaptor.forClass(ServiceWithApacheLog4jAndMdcHeaders.class);
Service service = new ServiceWithApacheLog4jAndMdcHeaders();
service.sayHello();
assertDiagnosticContext(logCaptor, "test-log4j-mdc", "hello-log4j");
}
@Test
void captureMdcHeadersWhereSlf4jIsUsed() {
logCaptor = LogCaptor.forClass(ServiceWithSlf4jAndMdcHeaders.class);
Service service = new ServiceWithSlf4jAndMdcHeaders();
service.sayHello();
assertDiagnosticContext(logCaptor, "test-slf4j-mdc", "hello-slf4j");
}
@Test
void captureLoggingEventsContainingKeyValuePairs() {
logCaptor = LogCaptor.forClass(ServiceWithSlf4jWhileUsingKeyValuePairs.class);
Service service = new ServiceWithSlf4jWhileUsingKeyValuePairs();
service.sayHello();
List<LogEvent> logEvents = logCaptor.getLogEvents();
assertThat(logEvents).hasSize(1);
LogEvent logEvent = logEvents.get(0);
assertThat(logEvent.getMessage()).isEqualTo("My grocery list");
List<Map.Entry<String, Object>> keyValuePairs = logEvent.getKeyValuePairs();
assertThat(keyValuePairs)
.hasSize(2)
.contains(new SimpleImmutableEntry<>("fruit", "apple"))
.contains(new SimpleImmutableEntry<>("vegetable", "tomato"));
}
@Test
void detachAppenderWithCloseMethod() {
Logger logger = (Logger) LoggerFactory.getLogger(this.getClass());
assertThat(fetchAppenders(logger)).isEmpty();
logCaptor = LogCaptor.forClass(this.getClass());
assertListAppender(logger);
logCaptor.close();
assertThat(fetchAppenders(logger)).isEmpty();
}
@Test
void detachAppenderWithAutoClosable() {
Logger logger = (Logger) LoggerFactory.getLogger(this.getClass());
assertThat(fetchAppenders(logger)).isEmpty();
try (LogCaptor ignored = LogCaptor.forClass(this.getClass())) {
assertListAppender(logger);
}
assertThat(fetchAppenders(logger)).isEmpty();
}
/**
* NopStatusListener disables the output of logs to the console. If the listener is present in a configuration file
* LogCaptor won't be able to provide the console appender as it does not exist at all. Getting the console appender should also not
* throw an exception when the NopStatusListener is present. Having the listener and calling the method {@link LogCaptor#disableConsoleOutput()}
* does not make sense as it is already disabled by the listener.
*/
@Test
void notProvideConsoleAppenderWhenNopStatusListenerIsPresentAsLogBackConfiguration() throws IOException, JoranException {
try (InputStream inputStream = this.getClass().getResourceAsStream("/logback-config-examples/logback-test.xml")) {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.reset();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(loggerContext);
configurator.doConfigure(inputStream);
}
logCaptor = LogCaptor.forClass(ServiceWithApacheLog4j.class);
assertThat(logCaptor.getConsoleAppender()).isEmpty();
}
@Test
void provideConsoleAppenderWhenNoNopStatusListenerIsPresentAsLogBackConfiguration() {
logCaptor = LogCaptor.forClass(ServiceWithApacheLog4j.class);
assertThat(logCaptor.getConsoleAppender()).isPresent();
}
@Test
void disableConsoleOutput() {
logCaptor = LogCaptor.forClass(ServiceWithApacheLog4j.class);
logCaptor.disableConsoleOutput();
Service service = new ServiceWithApacheLog4j();
try (ConsoleCaptor consoleCaptor = new ConsoleCaptor()) {
service.sayHello();
assertThat(logCaptor.getLogs()).hasSizeGreaterThan(0);
assertThat(consoleCaptor.getStandardOutput()).isEmpty();
logCaptor.enableConsoleOutput();
logCaptor.clearLogs();
service.sayHello();
assertThat(logCaptor.getLogs()).hasSizeGreaterThan(0);
assertThat(consoleCaptor.getStandardOutput()).hasSizeGreaterThan(0);
}
}
private static void assertListAppender(Logger logger) {
assertThat(fetchAppenders(logger))
.hasSize(1)
.first()
.isInstanceOf(InMemoryAppender.class)
.extracting(Appender::getName)
.isEqualTo("log-captor");
}
private static List<Appender<?>> fetchAppenders(Logger logger) {
return StreamSupport
.stream(Spliterators.spliteratorUnknownSize(logger.iteratorForAppenders(), Spliterator.ORDERED), false)
.collect(Collectors.toList());
}
private static void assertDiagnosticContext(LogCaptor logCaptor, String mdcKey, String mdcValue) {
List<LogEvent> logEvents = logCaptor.getLogEvents();
assertThat(logEvents).hasSize(2);
assertThat(logEvents.get(0).getDiagnosticContext())
.hasSize(1)
.extractingByKey(mdcKey)
.isEqualTo(mdcValue);
assertThat(logEvents.get(1).getDiagnosticContext()).isEmpty();
}
private static void assertLogMessages(LogCaptor logCaptor, LogMessage... logMessages) {
for (LogMessage logMessage : logMessages) {
switch (logMessage) {
case INFO:
assertThat(logCaptor.getInfoLogs()).containsExactly(logMessage.getMessage());
break;
case DEBUG:
assertThat(logCaptor.getDebugLogs()).containsExactly(logMessage.getMessage());
break;
case WARN:
assertThat(logCaptor.getWarnLogs()).containsExactly(logMessage.getMessage());
break;
case ERROR:
assertThat(logCaptor.getErrorLogs()).containsExactly(logMessage.getMessage());
break;
case TRACE:
assertThat(logCaptor.getTraceLogs()).containsExactly(logMessage.getMessage());
break;
default:
throw new IllegalArgumentException(logMessage.getLogLevel() + " level is not supported yet");
}
}
String[] expectedLogMessages = Arrays.stream(logMessages)
.map(LogMessage::getMessage)
.toArray(String[]::new);
assertThat(logCaptor.getLogs())
.hasSize(expectedLogMessages.length)
.containsExactly(expectedLogMessages);
}
@Nested
class ClearLogsShould {
private final LogCaptor logCaptor = LogCaptor.forClass(ServiceWithApacheLog4j.class);
@AfterEach
void clearLogs() {
logCaptor.clearLogs();
}
@Test
void captureLogging() {
Service service = new ServiceWithApacheLog4j();
service.sayHello();
assertThat(logCaptor.getInfoLogs()).containsExactly(LogMessage.INFO.getMessage());
assertThat(logCaptor.getDebugLogs()).containsExactly(LogMessage.DEBUG.getMessage());
assertThat(logCaptor.getErrorLogs()).containsExactly(LogMessage.ERROR.getMessage());
assertThat(logCaptor.getWarnLogs()).containsExactly(LogMessage.WARN.getMessage());
assertThat(logCaptor.getLogs())
.hasSize(4)
.containsExactly(
LogMessage.INFO.getMessage(),
LogMessage.WARN.getMessage(),
LogMessage.ERROR.getMessage(),
LogMessage.DEBUG.getMessage()
);
}
@Test
void captureLoggingWithTheSameLogCaptureInstance() {
Service service = new ServiceWithApacheLog4j();
service.sayHello();
assertLogMessages(logCaptor, LogMessage.INFO, LogMessage.WARN, LogMessage.ERROR, LogMessage.DEBUG);
}
}
private static class CustomClassLoader extends ClassLoader {
@Override
public Class<?> findClass(String name) {
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(name.replace(".", "/") + ".class");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
Objects.requireNonNull(inputStream);
int len = 0;
while ((len = inputStream.read()) != -1) {
outputStream.write(len);
}
byte[] bytes = outputStream.toByteArray();
return defineClass(name, bytes, 0, bytes.length);
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
}
}