001/** 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved. 004 * 005 * This program and the accompanying materials are dual-licensed under 006 * either the terms of the Eclipse Public License v1.0 as published by 007 * the Eclipse Foundation 008 * 009 * or (per the licensee's choosing) 010 * 011 * under the terms of the GNU Lesser General Public License version 2.1 012 * as published by the Free Software Foundation. 013 */ 014package ch.qos.logback.access.filter; 015 016import ch.qos.logback.access.spi.IAccessEvent; 017import ch.qos.logback.core.filter.Filter; 018import ch.qos.logback.core.spi.FilterReply; 019 020import javax.management.MBeanServer; 021import javax.management.ObjectName; 022import javax.management.StandardMBean; 023import java.lang.management.ManagementFactory; 024 025public class CountingFilter extends Filter<IAccessEvent> { 026 027 long total = 0; 028 final StatisticalViewImpl accessStatsImpl; 029 030 String domain = "ch.qos.logback.access"; 031 032 public CountingFilter() { 033 accessStatsImpl = new StatisticalViewImpl(this); 034 } 035 036 @Override 037 public FilterReply decide(IAccessEvent event) { 038 total++; 039 accessStatsImpl.update(); 040 return FilterReply.NEUTRAL; 041 } 042 043 public long getTotal() { 044 return total; 045 } 046 047 @Override 048 public void start() { 049 MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); 050 try { 051 ObjectName on = new ObjectName(domain + ":Name=" + getName()); 052 StandardMBean mbean = new StandardMBean(accessStatsImpl, StatisticalView.class); 053 if (mbs.isRegistered(on)) { 054 mbs.unregisterMBean(on); 055 } 056 mbs.registerMBean(mbean, on); 057 super.start(); 058 } catch (Exception e) { 059 addError("Failed to create mbean", e); 060 } 061 } 062 063 @Override 064 public void stop() { 065 super.stop(); 066 try { 067 MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); 068 ObjectName on = new ObjectName("totp:Filter=1"); 069 mbs.unregisterMBean(on); 070 } catch (Exception e) { 071 addError("Failed to unregister mbean", e); 072 } 073 } 074 075 public String getDomain() { 076 return domain; 077 } 078 079 public void setDomain(String domain) { 080 this.domain = domain; 081 } 082 083}