1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.access.common.filter;
15
16 import ch.qos.logback.access.common.spi.IAccessEvent;
17 import ch.qos.logback.core.filter.Filter;
18 import ch.qos.logback.core.spi.FilterReply;
19
20 import javax.management.MBeanServer;
21 import javax.management.ObjectName;
22 import javax.management.StandardMBean;
23 import java.lang.management.ManagementFactory;
24
25 public class CountingFilter extends Filter<IAccessEvent> {
26
27 long total = 0;
28 final StatisticalViewImpl accessStatsImpl;
29
30 String domain = "ch.qos.logback.access";
31
32 public CountingFilter() {
33 accessStatsImpl = new StatisticalViewImpl(this);
34 }
35
36 @Override
37 public FilterReply decide(IAccessEvent event) {
38 total++;
39 accessStatsImpl.update();
40 return FilterReply.NEUTRAL;
41 }
42
43 public long getTotal() {
44 return total;
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 }