2013-11-20 48 views
0

我需要/web-inf/logs文件夾在我的日誌文件,所以我想給的log4jlog4j的初始化之前設置系統屬性

我在聽衆嘗試這種代碼的相對路徑:

@Override 
public void contextInitialized(ServletContextEvent event) { 
    ServletContext context = event.getServletContext(); 
    System.setProperty("azraspinaRootPath", context.getRealPath("/")); 

} 

這個代碼的log4j.xml文件

<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy"> 
    <param name="FileNamePattern" value="${azraspinaRootPath}WEB-INF/logs23/hibernate-%d{yyyy-MM-dd}.gz" /> 
</rollingPolicy> 

和這行代碼在web.xml:

<listener> 
    <listener-class>ir.raysis.azraspina.startup.servlet.StartupListener</listener-class> 
</listener> 

但似乎log4j的這個監聽器之前初始化,因爲它存儲在home/web-inf/logs

我能做些什麼,使這項工作我的日誌文件?這可能是一個不好的做法,所以如果你知道在共享的tomcat中更好的做法,請告訴我。感謝

回答

1

希望這將幫助你

在web.xml中

<?xml version="1.0" encoding="UTF-8"?> 
<web-app id="log4j-webapp-demo" version="2.4" 
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 
    <servlet> 
     <servlet-name>Log4JTestServlet</servlet-name> 
     <servlet-class>test.Log4JTestServlet</servlet-class> 
    </servlet> 
    <servlet> 
     <servlet-name>Log4JInitServlet</servlet-name> 
     <servlet-class>test.Log4JInitServlet</servlet-class> 
     <init-param> 
      <param-name>log4j-properties-location</param-name> 
      <param-value>WEB-INF/log4j.properties</param-value> 
     </init-param> 
     <load-on-startup>1</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
     <servlet-name>Log4JTestServlet</servlet-name> 
     <url-pattern>/test</url-pattern> 
    </servlet-mapping> 
</web-app> 

在課堂上,

import org.apache.log4j.Logger; 

import java.io.*; 
import java.sql.SQLException; 
import java.util.*; 

public class log4jExample{ 



/* Get actual class name to be printed on */ 
static Logger log = Logger.getLogger( 
log4jExample.class.getName()); 

public static void main(String[] args) 
throws IOException,SQLException{ 

log.debug("Hello this is an debug message"); 
log.info("Hello this is an info message"); 
} 
} 
+0

感謝。我會測試它並回復你 – MoienGK

相關問題