java · 2021年3月25日 0

java自定义注解进行出参入参日志打印

  • 在实际的开发需求中,我们会对请求的入参和出参的信息打印,这些我们可以自定义一个注解来完成这些重复的冗余工作,还可以在此基础上进行日志的入表持久化,这样查日志的时候就可以不用再服务器上看了,可以在可视化界面进行查看
  • 首先定义一个注解名称为Log,参数只有一个接口的名称,一半用于接口层面,来进行入参和出参打印

    
    package com.sunyw.xyz.annotation;
    
    import java.lang.annotation.*;
    
    @Target({ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Log {
    
    /**
    * 请求接口名称
    *
    * @return
    */
    String name() default "default名称";
    }
- 切面定义和日志打印逻辑
package com.sunyw.xyz.annotation;

import com.alibaba.fastjson.JSON;
import com.sunyw.xyz.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;

/**
 * @Description: @Log注解解释器
 * @Author: sunyw
 * @CreateDate: 2021/1/31 23:14
 * @UpdateUser: sunyw
 * @UpdateDate: 2021/1/31 23:14
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Aspect
@Component
@Slf4j
public class LogAsp {

/**
 * 切点
 */
@Pointcut("@annotation(com.sunyw.xyz.annotation.Log)")
public void pointCut() {

}

/**
 * 环绕日志打印
 *
 * @param joinPoint
 * @return
 * @throws Throwable
 */
@Around("pointCut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    Logger log = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    Log annotation = method.getAnnotation(Log.class);
    if (null == annotation) {
        return joinPoint.getArgs();
    }
    String name = annotation.name();
    long startTime = System.currentTimeMillis();
    log.info("[环绕日志]>>>>>>>>>>>>>>>>>>>>>>>>>方法[{}]开始执行,开始时间{}", name, startTime);
    HttpServletRequest request = getRequest();
    log.info("[环绕日志]>>>>>>>>>>>>>>>>>>>>>>>>>请求方法路径为:{}", request.getRequestURL());
    StringBuilder params = new StringBuilder();
    //参数值
    Object[] argValues = joinPoint.getArgs();
    //参数名称
    String[] argNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
    if (argValues != null) {
        for (int i = 0; i < argValues.length; i++) {
            params.append(argNames[i]).append(":").append(argValues[i]);
        }
    }
    log.info("[环绕日志]>>>>>>>>>>>>>>>>>>>>>>>>>请求参数为:[{}]", params + "");
    Object proceed = joinPoint.proceed();
    log.info("[环绕日志]>>>>>>>>>>>>>>>>>>>>>>>>>响应参数为: [{}]", JSON.toJSON(proceed));
    log.info("[环绕日志]>>>>>>>>>>>>>>>>>>>>>>>>>执行完毕耗时 :{}", (System.currentTimeMillis() - startTime));
    return proceed;
}

/**
 * 异常日志打印
 *
 * @param joinPoint
 * @param e
 */
@AfterThrowing(pointcut = "pointCut()", throwing = "e")
public void throwIng(JoinPoint joinPoint, Throwable e) {
    log.info("[异常日志]>>>>>>>>>>>>>>>>>>>>>>>>>开始进行记录");
    String stackTrace = stackTrace(e);
    HttpServletRequest request = getRequest();
    String ipAddr = IpUtils.getIpAddr(request);
    log.info("[异常日志]>>>>>>>>>>>>>>>>>>>>>>>>>当前请求的Ip地址为:{}", ipAddr);
    log.info("[异常日志]>>>>>>>>>>>>>>>>>>>>>>>>>错误信息为:{}", stackTrace);
    log.info("[异常日志]>>>>>>>>>>>>>>>>>>>>>>>>>异常日志记录完毕");
    // TODO: 2021/1/31 未做数据库存储
}

/**
 * 堆栈异常获取
 *
 * @param throwable
 * @return
 */
private static String stackTrace(Throwable throwable) {
    StringWriter sw = new StringWriter();
    try (PrintWriter pw = new PrintWriter(sw)) {
        throwable.printStackTrace(pw);
        return sw.toString();
    }
}

/**
 * 获取HttpServletRequest
 *
 * @return
 */
private HttpServletRequest getRequest() {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
    assert servletRequestAttributes != null;
    return servletRequestAttributes.getRequest();
    }
}

- 使用
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210131232745620.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3N1b2RvZA==,size_16,color_FFFFFF,t_70)

- 结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210131232721912.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3N1b2RvZA==,size_16,color_FFFFFF,t_70)

- 日志保存的话,可以写一个异步的方法,获取一下请求的参数,开始时间结果时间返回结果以及traceId即可
- 源码地址[点击进入](https://gitee.com/sunyaowei/springbootlimit)