View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
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      // output the events as formatted by our layout
60      try {
61        this.encoder.doEncode(event);
62      } catch (IOException e) {
63      }
64  
65      // prepare for next event
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  }