1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.classic;
15
16 import ch.qos.logback.classic.net.testObjectBuilders.LoggingEventBuilderInContext;
17 import ch.qos.logback.classic.spi.ILoggingEvent;
18 import ch.qos.logback.classic.util.LogbackMDCAdapter;
19 import ch.qos.logback.core.UnsynchronizedAppenderBase;
20 import ch.qos.logback.core.read.ListAppender;
21 import ch.qos.logback.core.status.OnConsoleStatusListener;
22 import ch.qos.logback.core.testUtil.RandomUtil;
23 import org.junit.jupiter.api.BeforeEach;
24 import org.junit.jupiter.api.Test;
25 import org.slf4j.MDC;
26
27 import static org.junit.jupiter.api.Assertions.assertEquals;
28 import static org.junit.jupiter.api.Assertions.assertFalse;
29 import static org.junit.jupiter.api.Assertions.assertTrue;
30
31
32
33
34
35 public class AsyncAppenderTest {
36
37 String thisClassName = this.getClass().getName();
38 LoggerContext loggerContext = new LoggerContext();
39 LogbackMDCAdapter logbackMDCAdapter = new LogbackMDCAdapter();
40 AsyncAppender asyncAppender = new AsyncAppender();
41 ListAppender<ILoggingEvent> listAppender = new ListAppender<ILoggingEvent>();
42 OnConsoleStatusListener onConsoleStatusListener = new OnConsoleStatusListener();
43 LoggingEventBuilderInContext builder = new LoggingEventBuilderInContext(loggerContext, thisClassName,
44 UnsynchronizedAppenderBase.class.getName());
45 int diff = RandomUtil.getPositiveInt();
46
47 @BeforeEach
48 public void setUp() {
49 loggerContext.setMDCAdapter(logbackMDCAdapter);
50 onConsoleStatusListener.setContext(loggerContext);
51 loggerContext.getStatusManager().add(onConsoleStatusListener);
52 onConsoleStatusListener.start();
53
54 asyncAppender.setContext(loggerContext);
55 listAppender.setContext(loggerContext);
56 listAppender.setName("list");
57 listAppender.start();
58 }
59
60 @Test
61 public void eventWasPreparedForDeferredProcessing() {
62 asyncAppender.addAppender(listAppender);
63 asyncAppender.start();
64
65 String k = "k" + diff;
66 logbackMDCAdapter.put(k, "v");
67 asyncAppender.doAppend(builder.build(diff));
68 MDC.clear();
69
70 asyncAppender.stop();
71 assertFalse(asyncAppender.isStarted());
72
73
74 assertEquals(1, listAppender.list.size());
75 ILoggingEvent e = listAppender.list.get(0);
76
77
78 assertEquals("v", e.getMDCPropertyMap().get(k));
79 assertFalse(e.hasCallerData());
80 }
81
82 @Test
83 public void settingIncludeCallerDataPropertyCausedCallerDataToBeIncluded() {
84 asyncAppender.addAppender(listAppender);
85 asyncAppender.setIncludeCallerData(true);
86 asyncAppender.start();
87
88 asyncAppender.doAppend(builder.build(diff));
89 asyncAppender.stop();
90
91
92 assertEquals(1, listAppender.list.size());
93 ILoggingEvent e = listAppender.list.get(0);
94 assertTrue(e.hasCallerData());
95 StackTraceElement ste = e.getCallerData()[0];
96 assertEquals(thisClassName, ste.getClassName());
97 }
98 }