写在最前面: 本文要解决的问题: 1、实现一个Servlet /** * Log4J初始化
* @author XiongChun * @since 2011-04-26 */ public class Log4jInitServlet extends HttpServlet { /** * Servlet初始化 */ public void init(ServletConfig config) throws ServletException {
String root = config.getServletContext().getRealPath("/"); String log4jLocation = config.getInitParameter("log4jLocation"); System.setProperty("webRoot", root); if (G4Utils.isNotEmpty(log4jLocation)) { PropertyConfigurator.configure(root + log4jLocation); }
} } 2、web.xml加载这个servlet
<!-- 配置Log4j --> <servlet> <servlet-name>log4jInit</servlet-name> <servlet-class>org.eredlab.g4.rif.util.Log4jInitServlet</servlet-class> <init-param> <param-name>log4jLocation</param-name> <param-value>WEB-INF/classes/log4j.properties</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> 3、此时在log4j.properties中就可以使用相对路径了,如下:
#Rlogfile log4j.appender.Rlogfile=org.apache.log4j.RollingFileAppender log4j.appender.Rlogfile.layout=org.apache.log4j.PatternLayout log4j.appender.Rlogfile.layout.ConversionPattern=%d %p [%c] - <%m>%n log4j.appender.Rlogfile.File=${webRoot}/logs/eRedG4.log log4j.appender.Rlogfile.MaxFileSize=2048KB log4j.appender.Rlogfile.MaxBackupIndex=10 批注:写完才发现,其实这种方式用的也是绝对路径,只不过是用动态获取绝对路径的方法来达到类似相对路径的效果了。 |