spring boot使用springAOP实现记录日志

package com.server.aspect;

import com.mapper.RflogMapper;
import com.server.pojo.Rflog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
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 java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Aspect
@Component
@Slf4j
public class WebLogAspect {

    @Autowired
    RflogMapper rflogMapper;

    private static final ThreadLocal<Date> beginTimeThreadLocal = new NamedThreadLocal<Date>("ThreadLocal beginTime");
    private static final ThreadLocal<Rflog> logThreadLocal =  new NamedThreadLocal<Rflog>("ThreadLocal log");

    public WebLogAspect() {
    }

    /**
     * 定义请求日志切入点,其切入点表达式有多种匹配方式,这里是指定路径
     */
    @Pointcut("execution(public * com.ruifeng.tjtaxiqy.server.controller.*.*(..))")
    public void webLogPointcut() {
    }

    /**
     * 前置通知:
     * 1. 在执行目标方法之前执行,比如请求接口之前的登录验证;
     * 2. 在前置通知中设置请求日志信息,如开始时间,请求参数,注解内容等
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLogPointcut()")
    public void doBefore(JoinPoint joinPoint) {

        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //打印请求的内容
        Date beginTime = new Date();
        beginTimeThreadLocal.set(beginTime);


        log.info("请求开始时间:{}", LocalDateTime.now());
        log.info("请求Url : {}", request.getRequestURL().toString());
        log.info("请求方式 : {}", request.getMethod());
        log.info("请求ip : {}", request.getRemoteAddr());
        log.info("请求方法 : ", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("请求参数 : {}" , Arrays.toString(joinPoint.getArgs()));
        Map<String, Object> header = new HashMap<>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            header.put(key, value);
        }
        log.info("请求头:{}", JSONObject.wrap(header).toString());

        Rflog build = Rflog.builder().starttime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()))
                .url(request.getRequestURL().toString()).requestMethod(request.getMethod()).requestIp(request.getRemoteAddr())
                .requestMethod(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName())
                .requestParam(Arrays.toString(joinPoint.getArgs()).length() > 1000 ? Arrays.toString(joinPoint.getArgs()).substring(0, 1000) : Arrays.toString(joinPoint.getArgs()))
                .requestHeader(JSONObject.wrap(header).toString().length() > 1000 ? JSONObject.wrap(header).toString().substring(0, 1000) : JSONObject.wrap(header).toString())
                .build();
        logThreadLocal.set(build);

    }

    /**
     * 返回通知:
     * 1. 在目标方法正常结束之后执行
     * 1. 在返回通知中补充请求日志信息,如返回时间,方法耗时,返回值,并且保存日志信息
     *
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "webLogPointcut()")
    public void doAfterReturning(Object ret) throws Throwable {
        Rflog rflog = logThreadLocal.get();
        Date startTime = beginTimeThreadLocal.get();
        int days = (int) (new Date().getTime() - startTime.getTime());
        rflog.setEndtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()));
        rflog.setTimetaken(days);
//        System.out.println("url:"+rflog.getUrl().length());
//        System.out.println("request_ip:"+rflog.getRequestIp().length());
//        System.out.println("request_method:"+rflog.getRequestMethod().length());
//        System.out.println("request_param:"+rflog.getRequestParam().length());
//        System.out.println("request_header:"+rflog.getRequestHeader().length());
        rflog.setRequestResult(ret.toString().length() > 1000 ? ret.toString().substring(0, 1000) : ret.toString());
        rflog.setRequestState("success");
        rflogMapper.insert(rflog);
        log.info("请求结束时间:{}", new Date());
        log.info("请求耗时:{}", days);
        // 处理完请求,返回内容
        log.info("请求返回 : {}", ret);
    }

    /**
     * 异常通知:
     * 1. 在目标方法非正常结束,发生异常或者抛出异常时执行
     * 1. 在异常通知中设置异常信息,并将其保存
     *
     * @param throwable
     */
    @AfterThrowing(value = "webLogPointcut()", throwing = "throwable")
    public void doAfterThrowing(Throwable throwable) {
        Rflog rflog = logThreadLocal.get();
        Date startTime = beginTimeThreadLocal.get();
        int days = (int) (new Date().getTime() - startTime.getTime());
        rflog.setEndtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()));
        rflog.setTimetaken(days);
        rflog.setException(throwable.getMessage().length()>1000?throwable.getMessage().substring(0,1000):throwable.getMessage());
        rflog.setRequestState("failed");
        rflogMapper.insert(rflog);
        // 保存异常日志记录
        log.error("发生异常时间:{}", LocalDateTime.now());
        log.error("抛出异常:{}", throwable.getMessage());
    }
}

把上面的切面类配置到和controller层一个文件夹下 ,对controller层的操作进行记录。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iamlzjoco

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值