1
2
3
4
5
6
7
8
9
10
11
12
13
14 package chapters.appenders;
15
16 import ch.qos.logback.classic.spi.ILoggingEvent;
17 import ch.qos.logback.core.AppenderBase;
18 import ch.qos.logback.core.Layout;
19
20 public class CountingConsoleAppender extends AppenderBase<ILoggingEvent> {
21 static int DEFAULT_LIMIT = 10;
22 int counter = 0;
23 int limit = DEFAULT_LIMIT;
24
25 Layout<ILoggingEvent> layout;
26
27 public void setLimit(int limit) {
28 this.limit = limit;
29 }
30
31 public int getLimit() {
32 return limit;
33 }
34
35 @Override
36 public void start() {
37 if (this.layout == null) {
38 addError("No layout set for the appender named [" + name + "].");
39 return;
40 }
41
42 String header = layout.getFileHeader();
43 System.out.print(header);
44 super.start();
45 }
46
47 public void append(ILoggingEvent event) {
48 if (counter >= limit) {
49 return;
50 }
51
52 String eventStr = this.layout.doLayout(event);
53
54 System.out.print(eventStr);
55
56
57 counter++;
58 }
59
60 public Layout<ILoggingEvent> getLayout() {
61 return layout;
62 }
63
64 public void setLayout(Layout<ILoggingEvent> layout) {
65 this.layout = layout;
66 }
67 }