View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2009, 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 chapter4;
15  
16  import ch.qos.logback.classic.spi.ILoggingEvent;
17  import ch.qos.logback.core.AppenderBase;
18  
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    public CountingConsoleAppender() {
26    }
27  
28    public void setLimit(int limit) {
29      this.limit = limit;
30    }
31  
32    public int getLimit() {
33      return limit;
34    }  
35    
36    @Override
37    public void start() {
38      if (this.layout == null) {
39        addError("No layout set for the appender named ["+ name +"].");
40        return;
41      }
42      
43      super.start();
44    }
45  
46    public void append(ILoggingEvent event) {
47      if (counter >= limit) {
48        return;
49      }
50      // output the events as formatted by our layout
51      System.out.print(this.layout.doLayout(event));
52  
53      // prepare for next event
54      counter++;
55    }
56  }