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 ch.qos.logback.access.filter;
15  
16  import ch.qos.logback.core.filter.Filter;
17  import ch.qos.logback.core.spi.FilterReply;
18  
19  import javax.management.MBeanServer;
20  import javax.management.ObjectName;
21  import javax.management.StandardMBean;
22  import java.lang.management.ManagementFactory;
23  
24  public class CountingFilter extends Filter {
25  
26    long total = 0;
27    final StatisticalViewImpl accessStatsImpl;
28    
29    String domain = "ch.qos.logback.access";
30    
31    public CountingFilter() {
32      accessStatsImpl = new StatisticalViewImpl(this);
33    }
34    
35    @Override
36    public FilterReply decide(Object event) {
37      total++;
38      accessStatsImpl.update();
39      return FilterReply.NEUTRAL;
40    }
41  
42    public long getTotal() {
43      return total;
44    }
45    
46    
47    @Override
48    public void start() {
49      MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
50      try {
51        ObjectName on = new ObjectName(domain+":Name="+getName());
52        StandardMBean mbean = new StandardMBean(accessStatsImpl, StatisticalView.class);
53        if (mbs.isRegistered(on)) {
54            mbs.unregisterMBean(on);
55        }
56        mbs.registerMBean(mbean, on);
57        super.start();
58      } catch (Exception e) {
59        addError("Failed to create mbean", e);
60      }
61    }
62    
63    @Override
64    public void stop() {
65      super.stop();
66      try {
67        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
68        ObjectName on = new ObjectName("totp:Filter=1");
69        mbs.unregisterMBean(on);
70      } catch(Exception e) {
71        addError("Failed to unregister mbean", e);
72      }
73    }
74  
75    public String getDomain() {
76      return domain;
77    }
78  
79    public void setDomain(String domain) {
80      this.domain = domain;
81    }
82    
83  }