Log4j是一組強大的日誌組件,在項目中時常須要用它提供一些信息,這兩天學習了一下它的簡單配置。java
第一步,咱們須要導入log4j-1.2.14.jar到lib目錄下mysql
第二步,在src下創建log4j.properties文件。添加以下內容web
1 log4j.properties 2 log4j.rootLogger =INFO,stdout 3 log4j.logger.sedion=INFO,db 4 log4j.logger.W=WARN,W 5 log4j.logger.E=ERROR,E 6 7 #輸出到控制檯 8 log4j.appender.stdout = org.apache.log4j.ConsoleAppender 9 log4j.appender.stdout.Target = System.out 10 log4j.appender.stdout.layout = org.apache.log4j.PatternLayout 11 log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{1}:%L - %m%n 12 13 #輸出WARN級別日誌 14 log4j.appender.W =org.apache.log4j.RollingFileAppender 15 log4j.appender.W.File =${catalina.home}/logs/Test/Test_W.log 16 log4j.appender.W.Append =true 17 log4j.appender.W.Threshold =WARN 18 log4j.appender.W.layout = org.apache.log4j.PatternLayout 19 log4j.appender.W.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n 20 21 #輸出ERROR級別日誌 22 log4j.appender.E = org.apache.log4j.RollingFileAppender 23 log4j.appender.E.File = ${catalina.home}/logs/Test/Test_E.log 24 log4j.appender.E.Append = true 25 log4j.appender.E.layout = org.apache.log4j.PatternLayout 26 log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss} [ %t\:%r ] - [ %p ] %m%n 27 28 ####################### 29 30 # JDBC Appender 31 32 ####################### 33 log4j.appender.db=org.apache.log4j.jdbc.JDBCAppender 34 log4j.appender.db.BufferSize=1 35 log4j.appender.db.driver=com.mysql.jdbc.Driver 36 log4j.appender.db.URL=jdbc:mysql://localhost:3306/test 37 log4j.appender.db.user=root 38 log4j.appender.db.password=123 39 log4j.appender.db.sql=insert into operate_log(class,method,createtime,loglevel,logmsg,username) values ("%C","%M","%d{yyyy-MM-dd HH\:mm\:ss}","%p","%m","%X{username}")
40 log4j.appender.db.layout=org.apache.log4j.PatternLayout
新建一個數據庫test和一張日誌表operate_log。spring
能夠看到數據庫中有個username動態字段,因此咱們要寫個過濾器
1 package config.filter; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 import javax.servlet.http.HttpServletRequest; 12 13 import org.apache.log4j.MDC; 14 15 16 public class Log4jFilter implements Filter 17 { 18 private final static int DEDAULT_USERID = 0; 19 public void destroy() 20 { 21 22 } 23 24 public void doFilter(ServletRequest req, ServletResponse rep, 25 FilterChain chain) throws IOException, ServletException 26 { 27 HttpServletRequest request = (HttpServletRequest)req; 28 String username = request.getParameter("username"); 29 30 if(username == null) 31 { 32 MDC.put("username", DEDAULT_USERID); 33 } 34 else 35 { 36 System.out.println("登錄名--"+username); 37 MDC.put("username", username); 38 } 39 40 41 chain.doFilter(req, rep); 42 } 43 44 public void init(FilterConfig arg0) throws ServletException 45 { 46 47 } 48 49 50 }
而後須要在web.xml中進行log4j.properties和過濾器的配置.sql
<!-- log4j配置 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- 過濾器配置 --> <filter> <filter-name>LogResFilter</filter-name> <filter-class>config.filter.Log4jFilter</filter-class> </filter> <filter-mapping> <filter-name>LogResFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping>
第三步,至此咱們配置已經所有完成,簡單寫個登錄來驗證一下。數據庫
jsp頁面很簡單,代碼便不列出來了.apache
寫個登錄實現類.tomcat
package sedion.zhr.controller; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import sedion.zhr.beans.UserBean; import sedion.zhr.service.iml.UserServiceIml; @Controller @RequestMapping("/action") public class LoginController { private static final Logger log_w= Logger.getLogger("W"); private static final Logger log_e = Logger.getLogger("E"); private Log logger = LogFactory.getLog(this.getClass()); @Resource(name = "UserService") private UserServiceIml serviceIml; @RequestMapping("/login.do") public String login(UserBean bean,HttpServletRequest request,HttpServletResponse response) throws Exception { List<UserBean> beans = this.serviceIml.finduser(new String[]{bean.getUsername(),bean.getPassword()}); if(!beans.isEmpty()) { log_w.warn("登錄成功--"); logger.info("登錄成功"); return "/index"; } else { log_e.error("登錄失敗--"); logger.error("登錄失敗"); return "/login"; } } }
將項目配置到tomcat上,啓動項目.app
能夠看到在安裝tomcat文件夾下的logs文件夾裏面出現個Test文件夾,裏面有兩個文本,初始大小都是0kb.jsp
而後咱們各登錄成功,登錄失敗一次。觀察到控制檯上輸出
而後發現先前兩個文本大小變爲1kb,裏面各有成功失敗的信息。
打開數據庫表裏面多了兩條數據。
測試成功。
最後記錄一下log4j配置中相關屬性
log4j日誌常見輸出級別有4級,由高到低依次是ERROR、WARN、INFO、DEBUG。
日誌輸出目的地
打印參數