切面日誌

 

直接上代碼

package com.XXX.datacenter.framework.web.log;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
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.util.Arrays;

/**
 * @Auther: liyongli
 * @Date: 2019/8/26 15:05
 * @Description:
 */
@Slf4j
@Aspect
@Component
public class LogService {

    @Pointcut("execution(public * com.XXX.datacenter.framework.web.controller..*(..))")
    public void log() {

    }

    //統計請求的處理時間
    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        startTime.set(System.currentTimeMillis());

//        System.out.println("我是前置通知!!!");
        //獲取目標方法的參數信息
//        Object[] obj = joinPoint.getArgs();
//        Signature signature = joinPoint.getSignature();
//        //代理的是哪一個方法
//        System.out.println("方法:"+signature.getName());
//        //AOP代理類的名字
//        System.out.println("方法所在包:"+signature.getDeclaringTypeName());
//        //AOP代理類的類(class)信息
//        signature.getDeclaringType();
//        MethodSignature methodSignature = (MethodSignature) signature;
//        String[] strings = methodSignature.getParameterNames();
//        log.info("參數名:"+ Arrays.toString(strings));
//        log.info("參數值ARGS : " + Arrays.toString(joinPoint.getArgs()));
        // 接收到請求,記錄請求內容

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //記錄請求的內容
        log.info("HTTP_URL:"+request.getRequestURL().toString());
        log.info("HTTP_Method:"+request.getMethod());
        log.info("IP : " + request.getRemoteAddr());
        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] strings = methodSignature.getParameterNames();
        log.info("參數名:"+ Arrays.toString(strings));
        log.info("參數值ARGS : ");
        Arrays.stream(joinPoint.getArgs()).forEach(object -> log.info(JSON.toJSONString(object)));
//        log.info("參數值ARGS : " + Arrays.toString(joinPoint.getArgs()));

    }

    @AfterReturning(returning = "ret" , pointcut = "log()")
    public void doAfterReturning(Object ret){
        //處理完請求後,返回內容
        log.info("方法返回值:"+ JSON.toJSONString(ret) +",方法執行時間:"+ (System.currentTimeMillis() - startTime.get()));
    }




}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章