基于Spring AOP(面向切面) 实现方法执行前、执行后,日志输出

package com.*.*.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
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 javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Aspect
@Order(5)
@Component
@Slf4j
public class DefaultLogAop {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static Long millisecond = 0L;

    /**
     * 匹配需要打印的方法
     * 1)execution(* *(..))
     * //表示匹配所有方法
     * 2)execution(public * com. item.service.UserService.*(..))
     * //表示匹配com.item.server.UserService中所有的公有方法
     * 3)execution(* com.item.server..*.*(..))
     * //表示匹配com.item.server包及其子包下的所有方法
     */
    @Pointcut("execution(public * com.*.*.controller.*.*(..))")
    public void defultLog() {
    }

}

请求开始时间,请求地址,请求ip,执行前的参数输出

@Before("defultLog()")
public void doBefore(JoinPoint joinPoint) throws ParseException {
    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    StringBuffer sb = new StringBuffer();
    // 记录下请求内容
    sb.append(" --访问开始时间:" + sdf.format(new Date()))
            .append("--url: ").append(request.getRequestURL()).append(" --ip: ")
            .append(request.getRemoteAddr()).append(" --method: ")
            .append(joinPoint.getSignature().getDeclaringTypeName()).append(".")
            .append(joinPoint.getSignature().getName());
    //将时间转换成毫秒
    millisecond = System.currentTimeMillis();
    // 获取参数, 只取自定义的参数, 自带的HttpServletRequest, HttpServletResponse不管
    if (ObjectUtil.isNotNull(joinPoint.getArgs()) && joinPoint.getArgs().length > 0) {
        for (Object o : joinPoint.getArgs()) {
            if (o instanceof HttpServletRequest || o instanceof HttpServletResponse) {
                continue;
            }
            if(ObjectUtil.isNotNull(o)){
                sb.append(" --params: ").append(JSON.toJSONString(o.toString()));
            }
        }
    }
    log.info(sb.toString());
}

请求结束时间,响应时间,执行后返回参数输出

@AfterReturning(returning = "ret", pointcut = "defultLog()")
public void doAfterReturning(Object ret) throws ParseException {
    // 处理完请求,返回内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    long time = System.currentTimeMillis();
    log.info("--访问结束时间:" + sdf.format(new Date()) + "--url: "+ request.getRequestURL() + " --响应时间:" + (time - millisecond) + "ms" + " --response : " + JSON.toJSONString(ret));
}


版权声明:本文为YuChen954原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
THE END
< <上一篇
下一篇>>