1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core;
15
16 import java.io.BufferedReader;
17 import java.io.File;
18 import java.io.FileReader;
19 import java.io.IOException;
20 import java.util.concurrent.CountDownLatch;
21
22 import org.junit.jupiter.api.Assertions;
23 import org.junit.jupiter.api.BeforeEach;
24
25 import ch.qos.logback.core.contention.RunnableWithCounterAndDone;
26 import ch.qos.logback.core.encoder.EchoEncoder;
27 import ch.qos.logback.core.status.OnConsoleStatusListener;
28 import ch.qos.logback.core.testUtil.CoreTestConstants;
29 import ch.qos.logback.core.testUtil.RandomUtil;
30 import org.junit.jupiter.api.Test;
31
32 public class PrudentFileAppenderInterruptTest {
33
34 FileAppender<Object> fa = new FileAppender<Object>();
35 Context context = new ContextBase();
36 int diff = RandomUtil.getPositiveInt();
37 String outputDirStr = CoreTestConstants.OUTPUT_DIR_PREFIX + "resilience-" + diff + "/";
38 String logfileStr = outputDirStr + "output.log";
39
40 @BeforeEach
41 public void setUp() throws InterruptedException {
42 context.getStatusManager().add(new OnConsoleStatusListener());
43
44 File outputDir = new File(outputDirStr);
45 outputDir.mkdirs();
46
47 fa.setContext(context);
48 fa.setName("FILE");
49 fa.setPrudent(true);
50 fa.setEncoder(new EchoEncoder<Object>());
51 fa.setFile(logfileStr);
52 fa.start();
53 }
54
55 @Test
56 public void smoke() throws InterruptedException, IOException {
57 InterruptAndLogRunner runner = new InterruptAndLogRunner(fa);
58 Thread t = new Thread(runner);
59 t.start();
60
61 runner.latch.await();
62
63 fa.doAppend("hello not interrupted");
64
65 FileReader fr = new FileReader(logfileStr);
66 BufferedReader br = new BufferedReader(fr);
67
68 int totalLines = 0;
69 while (br.readLine() != null) {
70 totalLines++;
71 }
72 fr.close();
73 br.close();
74
75 Assertions.assertEquals(2, totalLines, "Incorrect number of logged lines "+outputDirStr);
76 }
77
78 class InterruptAndLogRunner extends RunnableWithCounterAndDone {
79 FileAppender<Object> fa;
80 CountDownLatch latch = new CountDownLatch(1);
81
82
83 InterruptAndLogRunner(FileAppender<Object> fa) {
84 this.fa = fa;
85 }
86
87 public void run() {
88 Thread.currentThread().interrupt();
89 fa.doAppend("hello interrupted");
90 latch.countDown();
91 }
92 }
93
94 }