实际上,我正在尝试为我的动态 Web 项目实现 log4j.file。这是我的web.xml
在这里,我只给出web.xml
了日志文件的代码
web.xml
<!-- Log File-->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<listener>
<listener-class>com.ss.logFile.startupListener.StartupListener</listener-class>
</listener>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
</web-app>
log4j.properties
log4j.rootLogger=ERROR, stdout, rollingFile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.File=WEB-INF/logs/application.log
log4j.appender.rollingFile.MaxFileSize=512KB
log4j.appender.rollingFile.MaxBackupIndex=10
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.rollingFile.Encoding=UTF-8
启动监听器
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
@WebServlet("/StartupListener")
public class StartupListener extends HttpServlet implements ServletContextListener {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
}
@Override
public void contextInitialized(ServletContextEvent sce) {
java.util.logging.Logger logger = null;
String log4jFile = sce.getServletContext().getInitParameter("log4jFileName");
DOMConfigurator.configure(sce.getServletContext().getRealPath(log4jFile));
logger = LogManager.getLogger(StartupListener.class.getName());
logger.debug("Loaded: " + log4jFile);
}
}
先生,实际上我对 log4j 很陌生,所以我不知道如何编写 log4j.xml 文件以及该文件 exaclty 的放置位置。请帮我解决这个问题。提前致谢