Log4j2 memory leak

2019-08-12 19:37发布

问题:

I've searched everywhere for a solution to this, and now I'm beginning to wonder whether it's really an issue.

I'm introducing log4j2 as the logger into my application and when I do that, on a reload, undeploy or stop of the Tomcat server 8.5.24, a memory leak is left, which only happens once I introduce the logger into the code.

My dependencies in pom.xml:

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.10.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.10.0</version>
</dependency>

My WebServlet:

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "Servlet", urlPatterns = {"/servlet"}, loadOnStartup = 1)
public class Servlet extends HttpServlet {

    private final Logger logger = LogManager.getLogger(Servlet.class);

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.info("doGet");

        PrintWriter out = response.getWriter();
        out.print("Servlet loaded");
        out.flush();
        out.close();
    }

}

My log4j2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="Console">
            <PatternLayout pattern="%d %p %c %m%n" />
        </Console>
        <File name="File" bufferedIO="true" fileName="logs/log4j2-file-sync-${date:HH:MM:ss.SSS}.log">
            <PatternLayout pattern="%d %p %c %m%n" />
        </File>
    </Appenders>
    <Loggers>
        <Root level="all" includeLocation="false">
            <AppenderRef ref="Console" />
            <AppenderRef ref="File" />
        </Root>
    </Loggers>
</Configuration>

This is the error I'm getting:

The following web applications were stopped (reloaded, undeployed), but their
classes from previous runs are still loaded in memory, thus causing a memory
leak (use a profiler to confirm):
/myapp

回答1:

To answer my own question thanks to the advice of @RemkoPopma from the comments and @RalphGoers from the Tomcat JIRA board.

I only needed the following dependency in my pom.xml which also imports the core and api and which handles proper shutdown of the Log4J2.

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-web</artifactId>
    <version>2.10.0</version>
</dependency>

The specific documentation for this dependency can be found

https://logging.apache.org/log4j/2.x/manual/webapp.html



标签: java log4j2