栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

接口请求响应打印(java)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

接口请求响应打印(java)

相关代码
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.io.Serializable;
import java.util.*;


@Aspect
@Component
public class WebLogAspect {

    private final static Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    
    @Pointcut("execution(public * com.jimi.api.controller..*.*(..))")
    public void webLog() {}

    
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {}

    
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String uri = request.getRequestURI();

        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();

        // 获取请求头
        Enumeration enumeration = request.getHeaderNames();
        StringBuffer headers = new StringBuffer();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            headers.append(name + ":" + value).append(",");
        }

        // 获取请求参数
        Object[] objs = proceedingJoinPoint.getArgs();
        Set sets = new HashSet<>();
        for (Object obj : objs) {
            if (obj instanceof Serializable) {
                sets.add(obj);
            }
        }

        // 记录info日志
        StringBuilder logInfo = new StringBuilder();
        logInfo.append(":n");
        logInfo.append("+========================================= Start ==========================================n");
        // 记录请求源ip
        logInfo.append("| IP             : ").append(request.getRemoteAddr()).append("n");
        // 记录请求url
        logInfo.append("| URI            : ").append(uri).append("n");
        // 记录请求的方式
        logInfo.append("| HTTP Method    : ").append(request.getMethod()).append("n");
        // 记录类名和方法名
        logInfo.append("| Class Method   : ").append(proceedingJoinPoint.getSignature().getDeclaringTypeName())
                .append(".").append(proceedingJoinPoint.getSignature().getName()).append("n");
        // 记录请求头
        logInfo.append("| Request Headers: ").append(headers).append("n");
        // 记录请求参数
        logInfo.append("| Request Args   : ").append(JSON.toJSONString(sets)).append("n");
        // 打印出参
        logInfo.append("| Response Args  : ").append(JSON.toJSON(result)).append("n");
        // 执行耗时
        logInfo.append("| Time-Consuming : ").append(System.currentTimeMillis() - startTime).append("ms").append("n");
        logInfo.append("+========================================== End ===========================================n");
        logger.info(logInfo.toString());
        return result;
    }

    @AfterThrowing(pointcut="execution(public * com.jimi.api.controller..*.*(..))", throwing = "e")
    public void afterThrowingAdvice(JoinPoint joinpoint, Throwable e) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            logger.error("log error!!");
            return ;
        }
        HttpServletRequest request = attributes.getRequest();
        String uri = request.getRequestURI();

        // 获取请求头
        Enumeration enumeration = request.getHeaderNames();
        StringBuffer headers = new StringBuffer();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            headers.append(name + ":" + value).append(",");
        }

        // 记录info日志
        StringBuilder logInfo = new StringBuilder();
        logInfo.append(":n");
        logInfo.append("+========================================= Start ==========================================n");
        // 记录请求源ip
        logInfo.append("| IP             : ").append(request.getRemoteAddr()).append("n");
        // 记录请求uri
        logInfo.append("| URI            : ").append(uri).append("n");
        // 记录请求的方式
        logInfo.append("| HTTP Method    : ").append(request.getMethod()).append("n");
        // 记录类名和方法名
        logInfo.append("| Class Method   : ").append(joinpoint.getSignature().getDeclaringTypeName())
                .append(".").append(joinpoint.getSignature().getName()).append("n");
        // 记录请求头
        logInfo.append("| Request Headers: ").append(headers).append("n");
        // 记录请求参数
        logInfo.append("| Request Args   : ").append(Arrays.toString(joinpoint.getArgs())).append("n");
        logInfo.append("+======================================= Exception ========================================n");
        logger.info(logInfo.toString());
        throw e;
    }

    
    @After("webLog()")
    public void doAfter() {}
}
 
效果展示 

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号