Created
October 21, 2015 12:33
-
-
Save mbknor/34944ea4589a5fc6974c to your computer and use it in GitHub Desktop.
Workaround for Dropwizard / logback / newrellic issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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