Java web application 初始化log4j

Java web 應運中,通常狀況下,只需將log4j的配置文件** log4j.properties**或者 **log4j.xml**放置在web的根目錄下(WEB-INF\classes ),咱們就能夠便捷的以以下方式使用_log4j_:html

Logger logger = Logger.getLogger(MyServlet.class);
logger.debug("this is a debug log message");

若是將_log4j_的配置文件,放置在web 應用的其它目錄下,則須要顯示的以以下方式初始化_log4j_:java

String log4jConfigFile = "some/path/log4j.properties";
PropertyConfigurator.configure(log4jConfigFile);

這種初始化方式只會在web應運啓動的時候執行一次,推薦的方法是實現_ServletContextListener接口,在contextInitialized()_事件中實現初始化:web

public class ContextListener implements ServletContextListener {
 
    @Override
    public void contextInitialized(ServletContextEvent event) {
        // code to initialize log4j here...
    }
}

如下是在_Java Web應用程序中初始化和使用log4j_的步驟:apache

1. 建立 _log4j.properties_文件

# LOG4J configuration
log4j.rootLogger=DEBUG, Appender1,Appender2
 
log4j.appender.Appender1=org.apache.log4j.ConsoleAppender
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender1.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n
 
log4j.appender.Appender2=org.apache.log4j.FileAppender
log4j.appender.Appender2.File=D:/Logs/Log4jWebDemo.log
log4j.appender.Appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender2.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n

該配置文件建立了兩個基本的 appender,第一個是_ConsoleAppender,第二個FileAppender_(日誌記錄將會輸出至 D:/Logs/Log4jWebDemo.log)app

將_log4j.properties_放在 _WEB-INF_下ide

2.在web.xml文件裏配置log4j.properties文件位置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
     
    <display-name>Log4jWebDemo1</display-name>
     
    <context-param>
        <param-name>log4j-config-location</param-name>
        <param-value>WEB-INF/log4j.properties</param-value>
    </context-param>
     
</web-app>

3.實現ServletContextListener接口

用以下代碼建立一個實現了**ServletContextListener** 接口的類**ContextListener**測試

package net.codejava.servlet;
 
import java.io.File;
 
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
 
import org.apache.log4j.PropertyConfigurator;
 
@WebListener("application context listener")
public class ContextListener implements ServletContextListener {
 
    /**
     * Initialize log4j when the application is being started
     */
    @Override
    public void contextInitialized(ServletContextEvent event) {
        // initialize log4j here
        ServletContext context = event.getServletContext();
        String log4jConfigFile = context.getInitParameter("log4j-config-location");
        String fullPath = context.getRealPath("") + File.separator + log4jConfigFile;
         
        PropertyConfigurator.configure(fullPath);
         
    }
     
    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // do nothing
    }  
}

在_contextInitialized()_方法中,咱們讀取並構建了**log4j.properties絕對路徑,使用 PropertyConfigurator.configure() 對log4j用指定的properties**文件進行了初始化。this

note:url

Servlet 3.0 才支持** @WebListener註解,若是你使用的是Servlet 2.5**,請在web.xml中使用以下等價的配置:debug

<listener>
    <listener-class>net.codejava.servlet.ContextListener</listener-class>
</listener>

4.建立一個測試類

package net.codejava.servlet;
 
import java.io.IOException;
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 org.apache.log4j.Logger;
 
@WebServlet("/test")
public class TestLog4jServlet extends HttpServlet {
 
    static final Logger LOGGER = Logger.getLogger(TestLog4jServlet.class);
             
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
         
        LOGGER.info("This is a logging statement from log4j");
         
        String html = "<html><h2>Log4j has been initialized successfully!</h2></html>";
        response.getWriter().println(html);
    }
 
}

一樣若是你的web不支持Servlet 3.0,請在web.xml加入以下等價的配置:

<servlet>
    <display-name>TestServlet</display-name>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>net.codejava.servlet.TestLog4jServlet</servlet-class>
</servlet>
 
<servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/test</url-pattern>
</servlet-mapping>

5. 測試

啓動web應用輸入以下地址:

http://localhost:8080/Log4jWebDemo1/test

能夠在控制檯和** D:/Logs**下看到相關日誌的輸出

相關文章
相關標籤/搜索