1. 程式人生 > 實用技巧 >log4j輸出日誌到專案路徑

log4j輸出日誌到專案路徑

在使用log4j進行日誌檔案輸出時,並不能夠預設輸出到專案根目錄,或者輸出到相對路徑,只能輸出到絕對路徑。

經修改配置檔案得到有效解決:

1.配置監聽器

通過監聽器獲取專案絕對路徑,並且配置系統屬性變數

package com.wd.listener;
 
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener; @WebListener public class applicationListener implements ServletContextListener,ServletContextAttributeListener{ @Override public void contextDestroyed(ServletContextEvent arg0) { System.getProperties().remove("log4jDirKey"); } @Override
public void contextInitialized(ServletContextEvent arg0) { String log4jDir=arg0.getServletContext().getRealPath("/"); System.setProperty("log4jDirKey", log4jDir); } }

2.配置lolog4j.properties

使用${log4jDirKey}獲取專案根目錄,並且配置到log4j.properties中

 
log4j.rootCategory=ERROR, CONSOLE,LOGFILE
log4j.logger.com.wd.mapper.PeopleMapper
=DEBUG log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=-%p-%d{yyyy/MM/dd HH:mm:ss,SSS}-%l-%L-%m%n log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=${log4jDirKey}/myLogs.log log4j.appender.LOGFILE.Append=false log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=-%p-%d{yyyy/MM/dd HH:mm:ss,SSS}-%l-%L-%m%n