简体   繁体   中英

using Log4j2 in servlet 3.0

I am using Log4j2 for logging purpose in my web application. If I create any simple java class and call my logger , it works perfectly fine and print the logs in a file. However if I do the same in servlet class, it is not working. As specified in the documentation I have not configured anything related to log4j2 in web.xml.

Code for Web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns="http://xmlns.jcp.org/xml/ns/javaee"     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>SampleWebApp</display-name>
<welcome-file-list>
<welcome-file>Welcome.jsp</welcome-file>
</welcome-file-list>
</web-app>

Logging code in Servlet class:

public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger log=LogManager.getLogger(MyServlet.class);

I have not explicitly placed log4j2.xml file in WEB-INF folder ,since I have added this file in classpath , its automatically added in WEB-INF/classes after I build the project.

Am I missing some configurations?

Line of Code :

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        log.error("i am inside servlet");
        /*response.getWriter().append("Served at: ").append(request.getContextPath());*/
        System.out.println("GET called");

    }

log4j2.xml :

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration>
      <Appenders>
        <Console name="Console">
          <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <File name="MyFile" filename="C:/Users/jasleen_kathuria/Documents/logs/info.log">
        <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
      </Appenders>
<Loggers>
<logger name="MyServlet" level="TRACE">
        <AppenderRef ref="MyFile"/>
    </logger>
</Loggers>

You should say at least how you build/deploy your web-app, on which servlet container, and how you add things to classpath.

All the same, the main problem is probably the fact that you are not adding log4j2 jar in WEB-INF/lib and or it's configuration in WEB-INF/classes.

When you call your simple java class , you are relying to a different classpath from your web-app.

Make sure that log4j2.jar is deployed, for example you can build the war unzip it and see what it contains.

Well it got resolved after I restarted my Tomcat and cleared my Browser cache. I am able to see the logs being printed now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM