乐者为王

Do one thing, and do it well.

Servlet.init()中Log4j不能输出日志

web.xml配置文件:

1
2
3
4
5
6
7
8
9
10
<web-app>
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.example.learning.HelloServlet</servlet-class>
        <init-param>
            <param-name>log4jConfig</param-name>
            <param-value>/WEB-INF/log4j.properties</param-value>
        </init-param>
    </servlet>
</web-app>

log4j.properties配置文件:

1
2
3
4
log4j.rootLogger=ALL, Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%t] %37c %3x - %m%n

HelloServlet.java代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class HelloServlet extends HttpServlet {
    private Logger logger = Logger.getLogger(HelloServlet.class);

    public void init() throws ServletException {
        super.init();

        ServletConfig config = getServletConfig();
        ServletContext sc = getServletContext();

        String log4jConfig = config.getInitParameter("log4jConfig");
        System.out.println(log4jConfig);

        if (log4jConfig == null) {
            BasicConfigurator.configure();
        } else {
            PropertyConfigurator.configure(sc.getRealPath(log4jConfig));
        }

        logger.info("This is an info message!");
    }

    public void destroy() {
    }
}

程序运行没有问题,可就是不能在Console视图中输出日志信息,而且使用System.out.println()也不能输出,不过在把private Logger logger行注释掉后System.out.println()就可以输出了。查看TOMCAT_HOME/logs中的日志文件,发现有如下异常:

1
2
3
----- Root Cause -----
java.lang.NoClassDefFoundError: org/apache/log4j/Logger
  at com.example.learning.HelloServlet.<init>(HelloServlet.java:15)

找不到Logger类?是不是WEB-INF/lib目录下没有log4j.jar呢?转到WEB-INF/lib目录,果然没有发现log4j.jar文件。把log4j.jar拷过去再试一下,真的OK了。

Comments