Skip to content

Instantly share code, notes, and snippets.

@mbknor
Created October 21, 2015 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbknor/34944ea4589a5fc6974c to your computer and use it in GitHub Desktop.
Save mbknor/34944ea4589a5fc6974c to your computer and use it in GitHub Desktop.
Workaround for Dropwizard / logback / newrellic issue
package no.ngt.tech.slf4jwait;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.SubstituteLoggerFactory;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* Dropwizard uses both slf4j and logback.
* In its bootstrap-code it gets a logger via slf4j and casts it to logback.
* This can fail if slf4j / logback is not yet initialized properly.
* This mostly happens when using newrelic which slows the initialization process down.
*
* By using this PreMain-main-class we will wait to start the real app until slf4j / logback is properly inited.
*
* How to use it:
*
* If you normally start your app like this:
*
* com.ngt.MyMainClass arg1 arg 2
*
* You can use PreMain like this:
*
* no.ngt.tech.slf4jwait.PreMain com.ngt.MyMainClass arg1 arg 2
*
*/
public class PreMain {
static {
System.out.println("Waiting for slf4j to finish initialization");
while ( LoggerFactory.getILoggerFactory() instanceof SubstituteLoggerFactory){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
break;
}
}
}
public static void main(String[] args) throws Exception {
String realMainClass = args[0];
System.out.println("slf4j initialization finished - Starting mainClass: " + realMainClass);
String[] realArgs = Arrays.copyOfRange(args, 1, args.length);
Class mainClass = PreMain.class.getClassLoader().loadClass(realMainClass);
Method mainMethod = mainClass.getMethod("main", String[].class);
mainMethod.invoke(null, (Object)realArgs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment