1
2
3
4
5
6
7
8
9
10
11
12
13
14 package chapters.appenders;
15
16 import java.io.IOException;
17
18 import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
19 import ch.qos.logback.classic.spi.ILoggingEvent;
20 import ch.qos.logback.core.AppenderBase;
21
22
23 public class CountingConsoleAppender extends AppenderBase<ILoggingEvent> {
24 static int DEFAULT_LIMIT = 10;
25 int counter = 0;
26 int limit = DEFAULT_LIMIT;
27
28 PatternLayoutEncoder encoder;
29
30 public CountingConsoleAppender() {
31 }
32
33 public void setLimit(int limit) {
34 this.limit = limit;
35 }
36
37 public int getLimit() {
38 return limit;
39 }
40
41 @Override
42 public void start() {
43 if (this.encoder == null) {
44 addError("No layout set for the appender named ["+ name +"].");
45 return;
46 }
47
48 try {
49 encoder.init(System.out);
50 } catch (IOException e) {
51 }
52 super.start();
53 }
54
55 public void append(ILoggingEvent event) {
56 if (counter >= limit) {
57 return;
58 }
59
60 try {
61 this.encoder.doEncode(event);
62 } catch (IOException e) {
63 }
64
65
66 counter++;
67 }
68
69 public PatternLayoutEncoder getEncoder() {
70 return encoder;
71 }
72
73 public void setEncoder(PatternLayoutEncoder encoder) {
74 this.encoder = encoder;
75 }
76
77
78 }