View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * 
4    * Copyright (C) 1999-2006, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  
11  package chapter4;
12  
13  import ch.qos.logback.classic.spi.LoggingEvent;
14  import ch.qos.logback.core.AppenderBase;
15  
16  
17  public class CountingConsoleAppender extends AppenderBase<LoggingEvent> {
18    static int DEFAULT_LIMIT = 10;
19    int counter = 0;
20    int limit = DEFAULT_LIMIT;
21    
22    public CountingConsoleAppender() {
23    }
24  
25    public void setLimit(int limit) {
26      this.limit = limit;
27    }
28  
29    public int getLimit() {
30      return limit;
31    }  
32    
33    @Override
34    public void start() {
35      if (this.layout == null) {
36        addError("No layout set for the appender named ["+ name +"].");
37        return;
38      }
39      
40      super.start();
41    }
42  
43    public void append(LoggingEvent event) {
44      if (counter >= limit) {
45        return;
46      }
47      // output the events as formatted by our layout
48      System.out.print(this.layout.doLayout(event));
49  
50      // prepare for next event
51      counter++;
52    }
53  }