View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, 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 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          // output the events as formatted by patternLayout
52          String eventStr = this.layout.doLayout(event);
53  
54          System.out.print(eventStr);
55  
56          // prepare for next event
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  }