我需要/web-inf/logs
文件夹中的日志文件,所以我试图给出log4j的相对路径
我在监听器中尝试此代码:
@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中做更好的练习,请告诉我。感谢
答案 0 :(得分: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");
}
}