spring boot aop log拦截配置

星期一, 2020-05-25 | Author: Lee | JAVA-and-J2EE | 1,674 views

要记录web的入参和出参及方法执行情况,执行如下配置即可

package com.pomelolee.configuration;
 
import lombok.extern.slf4j.Slf4j;
 
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
 
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.multipart.MultipartFile;
 
@Slf4j
@Aspect
@Component
public class WebControllerLogConfig {
 
    @Pointcut("execution(public * com.pomelolee.endpoint.*.*(..))")
    public void webRecordLog() {
 
    }
 
    @Around("webRecordLog()")
    public Object process(ProceedingJoinPoint jp) throws Throwable {
        String className = jp.getSignature().getDeclaringTypeName();
        String methodName = ((MethodSignature) jp.getSignature()).getMethod().getName();
        String classMethod = className + "." + methodName;
        Object[] arguments = jp.getArgs();
        Object[] args = new Object[arguments.length];
        for(int i=0;i<arguments.length;i++) {
    	 if (arguments[i] instanceof ServletRequest || arguments[i] instanceof ServletResponse || arguments[i] instanceof MultipartFile) { 
             //ServletRequest不能序列化,从入参里排除,否则报异常:java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
             //ServletResponse不能序列化 从入参里排除,否则报异常:java.lang.IllegalStateException: getOutputStream() has already been called for this response
               continue;
           }
           args[i] = arguments[i];
        }
        log.info("===controller classMethod:{},input args:{} ====", classMethod, JsonKit.toJSONString(args));
        final StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object result = jp.proceed();
        stopWatch.stop();
        final String logMessage = StringUtils.leftPad(Long.toString(stopWatch.getTotalTimeMillis()), 5) + " ms ";
        log.info("the classMethod: {} cost time: {}",classMethod,logMessage);
        log.info("===controller  classMethod: {} ,input args:{} ====", classMethod, JsonKit.toJSONString(result));
        return result;
    }
}

比较完整,排除了 out等输出的异常情况

Tags: ,

文章作者: Lee

本文地址: https://www.pomelolee.com/2070.html

除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址

No comments yet.

Leave a comment

Search

文章分类

Links

Meta