1
votes

I am setting up a web app running on Tomcat 9.

To match code written elsewhere, we want to keep using log4j for the code in the web application.

I have the following defined in my build.gradle

implementation group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.13.3'
implementation group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.13.3'
runtimeOnly group: 'org.apache.logging.log4j', name: 'log4j-web', version: '2.13.3'

And both log4j-api-2.13.3.jar, log4j-core-2.13.3.jar and log4j-web-2.13.3.jar are present in WEB-INF/libs under my webapp folder.

My log4j configuration is in WEB-INF/classes/log4j.properties

# Root logger option
log4j.rootLogger=DEBUG, file

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender

#Redirect to Tomcat logs folder
log4j.appender.file.File=${catalina.base}/logs/my-application.log

log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

In my handler I create the logger and tries to log some info, but it does not show up anywhere.


@WebServlet(name = "MyServlet", urlPatterns = {"/test"}, loadOnStartup = 1)
public class MyServletextends HttpServlet {
    private static final Logger logger = LogManager.getLogger(MyServlet.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("Test");
        response.getWriter().print("Service is up and running!");
    }
}

In the localhost.2020-09-28.log logfile I get a message saying

28-Sep-2020 11:38:18.391 FINE [main] org.apache.catalina.core.StandardContext.filterStart  Starting filter 'log4jServletFilter'

So I assume that log4j is loaded correctly, at least I do not find any errors in any of the log files.

What configuration am I missing for being able to use log4j, and have it output to its own file?

2

2 Answers

1
votes

I found out that the problem was that I was setting up the properties as if I was using log4j, but in reality I was using log4j2.

I found this by enabling log4j debug by adding -Dlog4j.debug property to the start of the Tomcat service.

This showed that it was looking for properties files with names similar to log4j2.properties.

I also had to change the content of my properties file to be usable with log4j2. I used the examples from this website to help me create a new properties file.

0
votes

In my case, project had 2 SLF4J implementations, "log4j" and "logback". On application deployment catalina.out had this message "SLF4J: Class path contains multiple SLF4J bindings....". Removed logback by dependency exclusion in pom and after that file was created and populated by logs.

See this link https://www.baeldung.com/slf4j-classpath-multiple-bindings