001package org.avaje.ebeantest; 002 003import java.util.ArrayList; 004import java.util.List; 005 006import org.slf4j.LoggerFactory; 007 008import ch.qos.logback.classic.Level; 009import ch.qos.logback.classic.Logger; 010import ch.qos.logback.classic.LoggerContext; 011import ch.qos.logback.classic.spi.ILoggingEvent; 012import ch.qos.logback.core.UnsynchronizedAppenderBase; 013 014/** 015 * Helper that can collect the SQL that is logged via SLF4J. 016 * <p> 017 * Used {@link #start()} and {@link #stop()} to collect the logged messages that contain the 018 * executed SQL statements. 019 * <p> 020 * Internally this uses a Logback Appender to collect messages for org.avaje.ebean.SQL. 021 */ 022public class LoggedSql { 023 024 private static BasicAppender basicAppender = new BasicAppender(); 025 026 static { 027 028 LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); 029 030 basicAppender.setContext(lc); 031 032 Logger logger = (Logger) LoggerFactory.getLogger("org.avaje.ebean.SQL"); 033 logger.addAppender(basicAppender); 034 logger.setLevel(Level.TRACE); 035 logger.setAdditive(true); 036 } 037 038 /** 039 * Start collection of the logged SQL statements. 040 */ 041 public static List<String> start() { 042 return basicAppender.collectStart(); 043 } 044 045 /** 046 * Stop collection of the logged SQL statements return the list of captured messages that contain 047 * the SQL. 048 */ 049 public static List<String> stop() { 050 return basicAppender.collectEnd(); 051 } 052 053 private static class BasicAppender extends UnsynchronizedAppenderBase<ILoggingEvent> { 054 055 List<String> messages = new ArrayList<String>(); 056 057 @Override 058 protected void append(ILoggingEvent eventObject) { 059 if (started) { 060 messages.add(eventObject.getMessage()); 061 } 062 } 063 064 /** 065 * Start collection. 066 */ 067 List<String> collectStart() { 068 List<String> tempMessages = messages; 069 messages = new ArrayList<String>(); 070 // set started flag 071 start(); 072 return tempMessages; 073 } 074 075 /** 076 * End collection. 077 */ 078 List<String> collectEnd() { 079 // set stopped state 080 stop(); 081 List<String> tempMessages = messages; 082 messages = new ArrayList<String>(); 083 return tempMessages; 084 } 085 086 } 087}