Search code examples
javatomcatlogginglog4jlog4j2

How to delegate embedded tomcat logging to log4j


I'm trying to disable default java.util.logging for embedded tomcat. It works, but for some reason I still find some messages in the standard log.

Before:

2021-12-27 21:24:33 INFO   org.apache.coyote.AbstractProtocol init Initializing ProtocolHandler ["http-nio-8081"]
2021-12-27 21:24:33 INFO   org.apache.catalina.core.StandardService startInternal Starting service [Tomcat]
2021-12-27 21:24:33 INFO   org.apache.catalina.core.StandardEngine startInternal Starting Servlet engine: [Apache Tomcat/10.1.0-M7]
2021-12-27 21:24:33 INFO   org.apache.catalina.startup.ContextConfig getDefaultWebXmlFragment No global web.xml found
2021-12-27 21:24:35 INFO   org.apache.jasper.servlet.TldScanner scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
2021-12-27 21:24:35 INFO   org.apache.coyote.AbstractProtocol start Starting ProtocolHandler ["http-nio-8081"]

After:

2021-12-27 21:33:21 INFO   org.apache.coyote.AbstractProtocol init Initializing ProtocolHandler ["http-nio-8081"]
2021-12-27 21:33:23 INFO   org.apache.jasper.servlet.TldScanner scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
2021-12-27 21:33:23 INFO   org.apache.coyote.AbstractProtocol start Starting ProtocolHandler ["http-nio-8081"]

How I try to delegate the logging:

import org.apache.logging.log4j.jul.Log4jBridgeHandler;

import java.util.logging.Level;

public class Application {
    public static void main(String[] args) throws Exception {
        System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$-6s %2$s %5$s%6$s%n");

        fixLogger("org.apache.tomcat");
        fixLogger("org.apache.catalina");
        fixLogger("org.apache.jasper");
        fixLogger("org.apache.coyote");
        fixLogger("org.apache.juli");

        TomcatServer.INSTANCE.run();

    }

    private static void fixLogger(String name) {
        java.util.logging.Logger logger = java.util.logging.Logger.getLogger(name);
        logger.setLevel(Level.ALL);
        logger.setUseParentHandlers(false);
        logger.addHandler(new Log4jBridgeHandler(false, "", false));
    }
}

Solution

  • Solved the problem. I only had to use this before the first initialization of the LogManager:

    System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");