org.ehoffman.test.aspects.WaitForLogbackAdvice Maven / Gradle / Ivy
package org.ehoffman.test.aspects;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.SubstituteLoggerFactory;
/**
* Logback will not block if initialization is incomplete and we request a loggerfactory.
* Instead it will return a {@link SubstituteLoggerFactory}. This is very undesirable if
* LogbackCapture is used in multithreaded test suits. So instead we will force tests to wait.
*
* @author rex
*/
public class WaitForLogbackAdvice implements MethodInterceptor {
private static final int MAX_ITERATIONS = 10;
private static final int MILLISECONDS_TO_SLEEP = 1000;
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
ILoggerFactory factory = LoggerFactory.getILoggerFactory();
int count = 0;
while ((factory == null || SubstituteLoggerFactory.class.isAssignableFrom(factory.getClass()))
&& count < MAX_ITERATIONS) {
Thread.sleep(MILLISECONDS_TO_SLEEP);
factory = LoggerFactory.getILoggerFactory();
count++;
}
//did our best, wont wait forever for Logback to initialize;
System.out.println("Logback failed to initialize in 10 seconds");
return invocation.proceed();
}
}