首页 > 编程语言 >Java 代码

Java 代码

时间:2022-12-18 12:35:27浏览次数:41  
标签:Java org 代码 打印 request import logArray pjp

AOP 日志:需引入aop-start,lombok或任何一个日志框架

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class ProxyLog {
    /** 以 controller 包下定义的所有请求为切入点 */
    @Pointcut("execution(public * com.example.blog.controller..*.*(..))")
    public void webLog() {}

    /**
     * 环绕
     * @param
     * @return
     * @throws Throwable
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        String[] logArray=new String[6];
        Object result=null;
        //记录开始时间
        long startTime = System.currentTimeMillis();
        try{
            //before
            // 开始打印请求日志
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            // 打印请求 url
            logArray[0]=request.getRequestURL().toString();
            // 打印 Http method
            logArray[1]=request.getMethod();
            // 打印请求的 IP
            logArray[2]=request.getRemoteAddr();
            // 打印调用 controller 的全路径以及执行方法
            logArray[3]=pjp.getSignature().getDeclaringTypeName()+"."+pjp.getSignature().getName();
            // 打印请求入参
            logArray[4]=pjp.getArgs().toString();
            //执行方法
            result = pjp.proceed();

            //afterReturning
        }catch (Exception e){
            //afterThrowing

        }finally {
            //after
            // 执行耗时
            logArray[5]=String.valueOf(System.currentTimeMillis() - startTime).toString();
            log.info("\nURL            : {}\nHTTP Method    : {}\nIP             : {}\nClass Method   : {}\nRequest Args   : {}\nTime-Consuming : {} ms\n",
                    logArray[0],logArray[1],logArray[2],logArray[3],logArray[4],logArray[5]);
        }
        return result;
    }
}

 

标签:Java,org,代码,打印,request,import,logArray,pjp
From: https://www.cnblogs.com/leviAckman/p/16990167.html

相关文章