The effect

The following figure shows the demo method and the log results printed by the console after the method is executed

Log Object

@Data
public class LogBO {

    /** * request URI */
    private String requestURI;
    /** * method name */
    private String method;

    /** * method input */
    private Object input;

    /** * method output */
    private Object output;

    /** * Method time (ms) */
    private Long timeConsuming;

    /** * method call time */
    private Date date;


    public LogBO(a) {
        this.date = new Date();
        if (Objects.nonNull(RequestContext.getRequest())) {
            this.requestURI = RequestContext.getRequest().getRequestURI(); }}}Copy the code

Annotation

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {

}
Copy the code

Aspect

@Slf4j
@Aspect
@Component
public class LogAspect {

    @Pointcut("@annotation(com.xxx.demo.log.Log)")
    public void logPointCut(a) {
        //definition
    }

    @Around(value = "logPointCut()")
    public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        LogBO logBO = new LogBO();
        // get current method
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        logBO.setMethod(method.getDeclaringClass().getName() + "." + method.getName());
        Map<String, Object> input = this.getInput(joinPoint, method);
        logBO.setInput(input);
        long startTime = System.currentTimeMillis();
        // get method return
        Object output = joinPoint.proceed();
        logBO.setOutput(output);
        logBO.setTimeConsuming(System.currentTimeMillis() - startTime);
        log.info(JSONObject.toJSONString(logBO));
    }

    private Map<String, Object> getInput(ProceedingJoinPoint joinPoint, Method method) {
        // get parameter names
        String[] parameterNames = new DefaultParameterNameDiscoverer().getParameterNames(method);
        Object[] args = joinPoint.getArgs();
        Map<String, Object> params = new HashMap<>(8);
        if(parameterNames ! =null&& parameterNames.length ! =0) {
            for (int i = 0; i < parameterNames.length; i++) { params.put(parameterNames[i], args[i]); }}returnparams; }}Copy the code

Util

public class RequestContext {

    public static HttpServletRequest getRequest(a) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return Objects.isNull(requestAttributes) ? null: requestAttributes.getRequest(); }}Copy the code