通过@Aspect注解加通用日志

package com.yzf.api.report.config;
import com.alibaba.fastjson.JSON;
import com.atc.daizhang.framework.common.utils.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
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.Objects;
import java.util.UUID;

@Component
@Aspect
@Slf4j
public class RequestAspect {

    @Pointcut("@within(org.springframework.stereotype.Controller) || " +
            "@within(org.springframework.web.bind.annotation.RestController)")
    public void pointcut() {
    }


    @Around("pointcut()")
    public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder
                .getRequestAttributes())).getRequest();
        //IP地址
        String ipAddr = IPUtils.getIpAddressByRequest(request);
        String url = request.getRequestURL().toString();
        String uuid = UUID.randomUUID().toString();
        long startTime = System.currentTimeMillis();
        log.info("请求源IP:【{}】, 请求URL:【{}】, TraceId:【{}】, 请求参数:【{}】",
                ipAddr, url, uuid, joinPoint.getArgs());
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        log.info("请求源IP:【{}】, 请求URL:【{}】, TraceId:【{}】, 耗时:【{}】",
                ipAddr, url, uuid, endTime - startTime);
        return result;
    }

    //获取请求结果
    @AfterReturning(returning = "object" , pointcut = "pointcut()")
    public void doAfterReturing(Object object){
        log.info("response={}",JSON.toJSONString(object));
    }
}

 

通过

request.getQueryString()能够获取get请求的参数名

根据request.getMethod能够获取请求方式

你可能感兴趣的:(java)