标签:des style blog http io color ar os sp
Log4j是一组强大的日志组件,在项目中时常需要用它提供一些信息,这两天学习了一下它的简单配置。
第一步,我们需要导入log4j-1.2.14.jar到lib目录下
第二步,在src下建立log4j.properties文件。添加如下内容
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。
可以看到数据库中有个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和过滤器的配置.
<!-- 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。
日志输出目的地
打印参数
标签:des style blog http io color ar os sp
原文地址:http://www.cnblogs.com/zhrxidian/p/4099460.html