log4j 将web请求 日志输入到数据库

最近做的项目出现了某些功能打开太慢的问题,为了方便统计并优化,想到可以在系统中加个拦截器,记录每个请求的处理时间,并打印耗时,结合log4j ,将日志如初到数据库,方便进行统计。

 

首先创建自己的拦截器:

 

package com.tera.sys.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.apache.log4j.MDC;

/**
 * 日志拦截器
 * @author sun
 * @version 2018-9-21
 */
public class LogInterceptor  implements HandlerInterceptor {
    private final static Logger logger = Logger.getLogger("LogInterceptor");
    private static final ThreadLocal<Long> startTimeThreadLocal =
            new NamedThreadLocal<Long>("ThreadLocal StartTime");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        if (logger.isDebugEnabled()){
            long beginTime = System.currentTimeMillis();//1、开始时间
            startTimeThreadLocal.set(beginTime);        //线程绑定变量(该数据只有当前请求的线程可见)
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        if (modelAndView != null){
            logger.info("ViewName: " + modelAndView.getViewName());
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        if (logger.isDebugEnabled()){
            long beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量(开始时间)
            long endTime = System.currentTimeMillis();  //2、结束时间
            MDC.put("url",request.getRequestURI());
            logger.debug( endTime - beginTime );
        }

    }

}

  在sping 配置文件中新增如下配置:

<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/**"/>
               <!-- 拦截器不需要拦截的路径-->
              <mvc:exclude-mapping path="/static/**" />
<bean class="com.tera.sys.filter.LogInterceptor"/> </mvc:interceptor> </mvc:interceptors>

说明:

  1)mvc:mapping 拦截器路径配置

  2)mvc:exclude-mapping 拦截器不需要拦截的路径

 

 如果提示没有mvc,则需要在beans 里增加mvc,我的配置如下:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:task="http://www.springframework.org/schema/task" xmlns:jee="http://www.springframework.org/schema/jee"
	xsi:schemaLocation="
    	http://www.springframework.org/schema/beans  
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
		http://www.springframework.org/schema/tx  
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
		http://www.springframework.org/schema/aop  
		http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
		http://www.springframework.org/schema/context  
		http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/jee 
		http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
		http://www.springframework.org/schema/task
		http://www.springframework.org/schema/task/spring-task-3.0.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
">

  红色 部分即为mvc配置。

下面配置log4j.properties

 

log4j.logger.LogInterceptor = DEBUG, LogInterceptor

# Define the DB appender
log4j.appender.LogInterceptor=org.apache.log4j.jdbc.JDBCAppender

# Set JDBC URL
log4j.appender.LogInterceptor.URL=jdbc:mysql://127.0.0.1:3306/test

# Set Database Driver
log4j.appender.LogInterceptor.driver=com.mysql.jdbc.Driver

# Set database user name and password
log4j.appender.LogInterceptor.user=root
log4j.appender.LogInterceptor.password=root

# Set the SQL statement to be executed.
log4j.appender.LogInterceptor.sql=INSERT INTO %d{yyyyMM}LOGS  VALUES('%X{url}','%d{yyyy-MM-dd HH:mm:ss}','%C','%p','%m')

# Define the layout for file appender
log4j.appender.LogInterceptor.layout=org.apache.log4j.PatternLayout

其中表名是按月分的变量,例如201809LOGS,后面的 '%X{url}'是获取拦截器中定义的url,对应

 

MDC.put("url",request.getRequestURI());
posted @ 2018-09-25 16:36  北极白开水  阅读(522)  评论(0编辑  收藏  举报