网上可以找到的log4j的嵌入方式有2种:
1、将log4j.properties放在classpath中,一般是web-inf/classes下,缺点的缺乏灵活性
2、可以通过log4j的com.apache.jakarta.log4j.Log4jInit类,Spring的 org.springframework.web.util.Log4jConfigServlet和 org.springframework.web.util.ServletContextListener来进行嵌入。
如果项目是以war包形式发布到weblogic中时方法2将会遇到问题。war包在weblogic中是不会自动展开的,这一点与tommcat不一样,换句话说,你就不能通过绝对路径来得到资源,而要以另一种形式ServletContext.getResourceAsStream()来进行读取。方法2中说到的几个类都是先取到文件的绝对路径然后再来读取,在weblogic启动的时候会出现错误
Cannot set web app root system property when WAR file is not expanded。
那么只好自己来进行初始化了
下面的就是新鲜出炉的log4j初始化类和web.xml文件中的配置
- package util;
- import java.io.IOException;
- import java.util.Properties;
- import javax.servlet.http.HttpServlet;
- import org.apache.log4j.PropertyConfigurator;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class Log4jInit extends HttpServlet {
- public void init() {
- /**
- * apache中的调用方法
- * String prefix =getServletContext().getRealPath("/");
- *
- * String file = getInitParameter("log4j");
- * // if the log4j-init-file is not set, then no point in trying
- *
- * System.out.println("................log4j start");
- *
- * if(file != null) {
- *
- * PropertyConfigurator.configure(prefix+file);
- * }
- *
- */
- String file = getInitParameter("log4j");
- System.out.println("................log4j start");
- if (file != null) {
- Properties ps=new Properties();
- try {
- ps.load(getServletContext().getResourceAsStream(file));
- } catch (IOException e) {
- e.printStackTrace();
- }
- PropertyConfigurator.configure(ps);
- }
- <servlet>
- <servlet-name>log4jLoader</servlet-name>
- <servlet-class>util.Log4jInit</servlet-class>
- <init-param>
- <param-name>log4j</param-name>
- <param-value>/WEB-INF/log4j.properties</param-value>
- </init-param>
- <load-on-startup>0</load-on-startup>
- </servlet>
下面的话摘自网上:
那么,现在对于war应用可以成功运行,但如果现在不通过war部署,直接通过目录结构部署应用会不会又出现找不到资源的错误呢?请来看看ServletContext.getResourceAsStream的API文档,
Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is interpreted as relative to the current context root.
This method allows the servlet container to make a resource available to servlets from any source. Resources can be located on a local or remote file system, in a database, or in a .war file.
可见,通过getResourceAsStream可以获取包括本地文件系统、远程文件系统、war包等资源。不会出现上面担心的问题。
结论:在开发J2EE Web应用时,如果需要读取本应用中的文件,尽量使用ServletContext.getResourceAsStream进行,而不要使用文件IO。