Redirect Jersey JUL logging to Log4j2

人盡茶涼 提交于 2019-12-05 22:44:11

I would imagine that you have to set the system property at launch. Add code to your init method to see if setting the system property worked.

@PostConstruct
public void init() {
    String cn = "org.apache.logging.log4j.jul.LogManager";
    System.setProperty("java.util.logging.manager", cn);
    LogManager lm = LogManager.getLogManager();
    if (!cn.equals(lm.getClass().getName())) {
       try {
           ClassLoader.getSystemClassLoader().loadClass(cn);
       } catch (ClassNotFoundException cnfe) {
          throw new IllegalStateException("Jars not in system class path.", cnfe);
       }
       throw new IllegalStateException("Found " + lm.getClass().getName() + " set as launch param instead.");
    }
}

This actually works for the Jersey case though you still need to set the System property java.util.logging.manager=org.apache.logging.log4j.jul.LogManager

Instantiate your logger as normal for log4j2 for your general application logging. Then, explicitly instantiate a java.util.logging.Logger using org.apache.logging.log4j.jul.LogManager. This second Logger instance is then used to register a new LoggingFilter as can be seen here, using Jersey 2 Client for this example (verbose naming for clarity):

org.apache.logging.log4j.Logger logger = org.apache.logging.log4j.LogManager.getLogger(this.getClass().getName());

java.util.logging.Logger jerseyLogger = org.apache.logging.log4j.jul.LogManager.getLogManager().getLogger(this.getClass().getName());

jerseyLogger.setLevel(java.util.logging.Level.SEVERE); //OPTIONAL

Client client = ClientBuilder.newClient();
client.register(new LoggingFilter(jerseyLogger, false));

logger.info("App logging uses the normal logger");

Now, calls to logger work as expected and all of Jersey's jul logging output is directed back into log4j2 appenders as expected.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!