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 chapters.appenders; 015 016import ch.qos.logback.classic.spi.ILoggingEvent; 017import ch.qos.logback.core.AppenderBase; 018import ch.qos.logback.core.Layout; 019 020public class CountingConsoleAppender extends AppenderBase<ILoggingEvent> { 021 static int DEFAULT_LIMIT = 10; 022 int counter = 0; 023 int limit = DEFAULT_LIMIT; 024 025 Layout<ILoggingEvent> layout; 026 027 public void setLimit(int limit) { 028 this.limit = limit; 029 } 030 031 public int getLimit() { 032 return limit; 033 } 034 035 @Override 036 public void start() { 037 if (this.layout == null) { 038 addError("No layout set for the appender named [" + name + "]."); 039 return; 040 } 041 042 String header = layout.getFileHeader(); 043 System.out.print(header); 044 super.start(); 045 } 046 047 public void append(ILoggingEvent event) { 048 if (counter >= limit) { 049 return; 050 } 051 // output the events as formatted by patternLayout 052 String eventStr = this.layout.doLayout(event); 053 054 System.out.print(eventStr); 055 056 // prepare for next event 057 counter++; 058 } 059 060 public Layout<ILoggingEvent> getLayout() { 061 return layout; 062 } 063 064 public void setLayout(Layout<ILoggingEvent> layout) { 065 this.layout = layout; 066 } 067}