javaweb项目切面获取用户请求内容,详细打印用户名,请求地址,请求时间,进行用户操作记录

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Map;
import com.ddhd.tdwall.utils.JedisUtil;
import com.ddhd.tdwall.utils.LogAopUtil;
import com.google.gson.Gson;
import javassist.NotFoundException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import redis.clients.jedis.Jedis;

@Aspect
@Component("logAspect")
public class LogAspect {

    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
   protected static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(LogAspect.class);
   private String requestPath = null ; // 请求地址
   private String userName = null ; // 用户名
   private Map inputParamMap = null ; // 传入参数
   private Map outputParamMap = null; // 存放输出结果
   private long startTimeMillis = 0; // 开始时间
   private long endTimeMillis = 0; // 结束时间
   private String inputMap = null;


   /**
    *
    * @Title:doBeforeInServiceLayer
    * @Description: 方法调用前触发
    *  记录开始时间
    * @author shaojian.yu
    * @date 2014年11月2日 下午4:45:53
    * @param joinPoint
    */
   @Before("execution(* com.ddhd.tdwall.controller..*.*(..))")
   public void doBeforeInServiceLayer(JoinPoint joinPoint) {
      startTimeMillis = System.currentTimeMillis(); // 记录方法开始执行的时间
   }

   /**
    *
    * @Title:doAfterInServiceLayer
    * @Description: 方法调用后触发
    *  记录结束时间
    * @author shaojian.yu
    * @date 2014年11月2日 下午4:46:21
    * @param joinPoint
    */
   @After("execution(* com.ddhd.tdwall.controller..*.*(..))")
   public void doAfterInServiceLayer(JoinPoint joinPoint) {
      endTimeMillis = System.currentTimeMillis(); // 记录方法执行完成的时间
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if(requestAttributes==null){
                return;
            }
            HttpServletRequest request = requestAttributes.getRequest();
            // 打印请求内容
         logger.warn("===============请求内容===============");
         logger.warn("请求地址:" + request.getRequestURL().toString());
         logger.warn("请求方式:" + request.getMethod());
         logger.warn("请求类方法:" + joinPoint.getSignature());
         logger.warn("请求类方法参数:" + Arrays.toString(joinPoint.getArgs()));
            String token = request.getHeader("token");
            if(!"".equals(token)&&token!=null){
                Jedis jedis = JedisUtil.getJedis();
                userName = jedis.get(token+"id");
                jedis.close();
            }
            Object[] args = joinPoint.getArgs();
            String classType = joinPoint.getTarget().getClass().getName();
            Class clazz = Class.forName(classType);
            String clazzName = clazz.getName();
            String methodName = joinPoint.getSignature().getName(); // 获取方法名称
            // 获取参数名称和值
            StringBuffer sb = LogAopUtil.getNameAndArgs(this.getClass(), clazzName, methodName, args);
         logger.warn("请求用户名称"+userName);
         logger.warn("请求类方法参数名称和值:" + sb);
         logger.warn("请求时间"+endTimeMillis);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
   }

   /**
    *
    * @Title:doAround
    * @Description: 环绕触发
    * @author shaojian.yu
    * @date 2014年11月3日 下午1:58:45
    * @param pjp
    * @return
    * @throws Throwable
    */
/* @Around("execution(* com.ddhd.tdwall.controller..*.*(..))")
   public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
      *//**
       * 1.获取request信息
       * 2.根据request获取session
       * 3.从session中取出登录用户信息
       *//*
      Object result = null;// result的值就是被拦截方法的返回值
      return result;
   }*/

   /**
    *
    * @Title:printOptLog
    * @Description: 输出日志
    * @author shaojian.yu
    * @date 2014年11月2日 下午4:47:09
    */
   private void printOptLog() {
      Gson gson = new Gson(); // 需要用到google的gson解析包
      String optTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTimeMillis);
      System.out.println("user"+userName+"url"+requestPath+"param"+inputParamMap+"result"+outputParamMap);
      log.info("\n user:"+userName
            +"  url:"+requestPath+"; op_time:" + optTime + " pro_time:" + (endTimeMillis - startTimeMillis) + "ms ;"
            +" param:"+inputMap+";"+"\n result:"+gson.toJson(outputParamMap));
   }






   // 配置织入点
    @Pointcut("@annotation(com.ddhd.tdwall.interceptor.Log)")
    public void logPointCut() {
    }
 
    /**
     * 前置通知 用于拦截操作,在方法返回后执行
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
   handleLog(joinPoint, null);
    }
 
    /**
     * 拦截异常操作,有异常时执行
     * 
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfter(JoinPoint joinPoint, Exception e) {
   handleLog(joinPoint, e);
    }
 
    private void handleLog(JoinPoint joinPoint, Exception e) {
   try {
       // 获得注解
       Log controllerLog = getAnnotationLog(joinPoint);
       if (controllerLog == null) {
      return;
       }
       // 获得方法名称
       String className = joinPoint.getTarget().getClass().getName();
       String methodName = joinPoint.getSignature().getName();
       String action = controllerLog.action();
       String title = controllerLog.title();
       
       //打印日志,如有需要还可以存入数据库
       log.info(">>>>>>>>>>>>>模块名称:{}",title);
       log.info(">>>>>>>>>>>>>操作名称:{}",action);
       log.info(">>>>>>>>>>>>>类名:{}",className);
       log.info(">>>>>>>>>>>>>方法名:{}",methodName);
   } catch (Exception exp) {
       // 记录本地异常日志
       log.error("==前置通知异常==");
       log.error("异常代码:{}", exp.getClass().getName());
       log.error("异常信息:{}", exp.getMessage());
       log.error("错误信息", exp);
   }
    }
 
    /**
     * 是否存在注解,如果存在就获取
     */
    private static Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
   Signature signature = joinPoint.getSignature();
   MethodSignature methodSignature = (MethodSignature) signature;
   Method method = methodSignature.getMethod();
   if (method != null) {
       return method.getAnnotation(Log.class);
   }
   return null;
    }





}

你可能感兴趣的:(java)