001package org.javasimon.callback.logging;
002
003/**
004 * Log template that logs something every N invocations of the {@link #isEnabled(Object)} method.
005 *
006 * @author gquintana
007 */
008public class CounterLogTemplate<C> extends DelegateLogTemplate<C> {
009
010        /** Counter max value corresponds to N value. */
011        private final int counterMax;
012        /** Counter value. */
013        private int counter;
014
015        /**
016         * Constructor.
017         *
018         * @param delegate Concrete log template
019         * @param counterMax Logging period
020         */
021        public CounterLogTemplate(LogTemplate delegate, int counterMax) {
022                super(delegate);
023                this.counterMax = counterMax;
024                this.counter = 1;
025        }
026
027        /**
028         * Returns counter max value, corresponding to logging period.
029         *
030         * @return Counter max
031         */
032        public int getCounterMax() {
033                return counterMax;
034        }
035
036        /**
037         * Returns counter value.
038         *
039         * @return counter value
040         */
041        public int getCounter() {
042                return counter;
043        }
044
045        /**
046         * Increments counter.
047         *
048         * @return true if counter looped and returned to 0
049         */
050        private boolean incrementCounter() {
051                boolean loop = (counter >= counterMax);
052                counter = loop ? 1 : counter + 1;
053                return loop;
054        }
055
056        @Override
057        protected boolean isEnabled(C context) {
058                return super.isEnabled(context) && incrementCounter();
059        }
060
061        @Override
062        protected void log(String message) {
063                super.log(message);
064        }
065}