Log4j是一組強大的日志組件,在項目中時常需要用它提供一些信息,這兩天學習了一下它的簡單配置。
第一步,我們需要導入log4j-1.2.14.jar到lib目錄下
第二步,在src下建立log4j.properties文件。添加如下內容
log4j.properties
log4j.rootLogger =INFO,stdout
log4j.logger.sedion=INFO,db
log4j.logger.W=WARN,W
log4j.logger.E=ERROR,E
#輸出到控制台
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{1}:%L - %m%n
#輸出WARN級別日志
log4j.appender.W =org.apache.log4j.RollingFileAppender
log4j.appender.W.File =${catalina.home}/logs/Test/Test_W.log
log4j.appender.W.Append =true
log4j.appender.W.Threshold =WARN
log4j.appender.W.layout = org.apache.log4j.PatternLayout
log4j.appender.W.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
#輸出ERROR級別日志
log4j.appender.E = org.apache.log4j.RollingFileAppender
log4j.appender.E.File = ${catalina.home}/logs/Test/Test_E.log
log4j.appender.E.Append = true
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss} [ %t\:%r ] - [ %p ] %m%n
#######################
# JDBC Appender
#######################
log4j.appender.db=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.db.BufferSize=1
log4j.appender.db.driver=com.mysql.jdbc.Driver
log4j.appender.db.URL=jdbc:mysql://localhost:3306/test
log4j.appender.db.user=root
log4j.appender.db.password=123
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}")
log4j.appender.db.layout=org.apache.log4j.PatternLayout
新建一個數據庫test和一張日志表operate_log。
可以看到數據庫中有個username動態字段,所以我們要寫個過濾器
package config.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.MDC;
public class Log4jFilter implements Filter
{
private final static int DEDAULT_USERID = 0;
public void destroy()
{
}
public void doFilter(ServletRequest req, ServletResponse rep,
FilterChain chain) throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest)req;
String username = request.getParameter("username");
if(username == null)
{
MDC.put("username", DEDAULT_USERID);
}
else
{
System.out.println("登陸名--"+username);
MDC.put("username", username);
}
chain.doFilter(req, rep);
}
public void init(FilterConfig arg0) throws ServletException
{
}
}
然後需要在web.xml中進行log4j.properties和過濾器的配置.
復制代碼
<!-- 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頁面很簡單,代碼便不列出來了.
寫個登陸實現類.
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上,啟動項目.
可以看到在安裝tomcat文件夾下的logs文件夾裡面出現個Test文件夾,裡面有兩個文本,初始大小都是0kb.
然後我們各登陸成功,登陸失敗一次。觀察到控制台上輸出
然後發現先前兩個文本大小變為1kb,裡面各有成功失敗的信息。
打開數據庫表裡面多了兩條數據。
測試成功。
最後記錄一下log4j配置中相關屬性
log4j日志常見輸出級別有4級,由高到低依次是ERROR、WARN、INFO、DEBUG。
日志輸出目的地
打印參數
Log4j配置詳解 http://www.linuxidc.com/Linux/2014-10/108401.htm
Apache Log4j 2 更多內容請看: http://logging.apache.org/log4j/2.x/
Log4j入門使用教程 http://www.linuxidc.com/Linux/2013-06/85223.htm
Log4j 日志詳細用法 http://www.linuxidc.com/Linux/2014-09/107303.htm
Hibernate配置Log4j顯示SQL參數 http://www.linuxidc.com/Linux/2013-03/81870.htm
Log4j學習筆記(1)_Log4j 基礎&配置項解析 http://www.linuxidc.com/Linux/2013-03/80586.htm
Log4j學習筆記(2)_Log4j配置示例&Spring集成Log4j http://www.linuxidc.com/Linux/2013-03/80587.htm
Log4j 的詳細介紹:請點這裡
Log4j 的下載地址:請點這裡