Springboot AOP aspect oriented programming, lower part: use AOP aspect technology to create access logs for API interfaces!

1. Introduction

Above, we have learned the basic and related knowledge of AOP aspect oriented programming and learned that it can create monitoring logs for programs without modifying the source code. In this paper, we carry out practice and use AOP aspect technology to create a unified access log for the mainstream restful API interface to record login IP, access methods, incoming parameters and other information.

2. Project structure and ideas

Project architecture: it acts on the standard restful API interface and does not set the login and authentication mechanism temporarily.

Idea: add a Before aspect without modifying any interface source code. The pointcut includes all classes, interfaces and methods under the API interface, and record the incoming parameters.

3. Log schema

(1) Interface IP address: provided by ServletRequestAttributes(getRequestURL()). ServletRequestAttributes is a ThreadLocal encapsulated by spring MVC, which saves the HttpServletRequest object of each Http request.

(2) IP address of the opposite side of the access interface: provided by ServletRequestAttributes(getRemoteAddr()).

(3) Interface class path name: provided by facet connection point joinpoint (getsignature(). Getdeclarangtypename()).

(4) Interface method name: provided by facet connection point JoinPoint(getSignature().getName()).

(5) Incoming parameters: provided by the facet connection point JoinPoint(getArgs()).

4. Project structure tree

There used to be an entity class Book and a restful API interface BookRepository, which is used to implement basic operations such as query get, modify put, add post, delete, etc. we do not make any source code modifications to the interface. We create an Aoplog class under the top-level package to implement AOP aspects and access log output.

  5. Aoplog code implementation

package com.example.demohelloworld.restful;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
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.util.Arrays;

@Component
@Aspect
public class Aoplog {
    //Define log output
    Logger logger= LoggerFactory.getLogger(this.getClass());
    //Define pointcuts
    @Pointcut("execution(* com.example.demohelloworld.restful.APIRepository.*.*(..))")
    public void getlog(){
    }
    //Build a Before pre notification, which is executed Before the method is executed to obtain the passed in parameters
    @Before(value = "getlog()")
    public void before(JoinPoint joinPoint){
        //Get Http provider request information through ServletRequestAttributes
        ServletRequestAttributes attributes= (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        //Interface IP address
        logger.info("url={}",request.getRequestURL());
        //IP address of the other side of the access interface
        logger.info("ip={}",request.getRemoteAddr());
        //Interface classpath name
        logger.info("class={}",joinPoint.getSignature().getDeclaringTypeName());
        //Interface method name
        logger.info("method={}",joinPoint.getSignature().getName());
        //Pass in the parameter in the format of Object [], and use Arrays.deepToString to convert
        logger.info("args={}", Arrays.deepToString(joinPoint.getArgs()));
    }
}

6. Start test  

We started the project and used POSTMAN to access the API interface:

findById queries a single piece of data, and the access log output is as follows:

 

For findAll batch query, the access log output is as follows. For the input parameters, we have added paging, number of entries per page and flashback by ID:

 

 

 

save adds Book data, and the access log output is as follows:

 

 

7. Summary  

AOP aspect programming can easily realize system monitoring, log output and other functions without modifying the source code. It is an independent module for maintenance.

Of course, there are many application scenarios for AOP. This paper only gives an example of the basic application of access log, which needs to be explored and practiced in the future.

Tags: Java Spring Boot AOP RESTful

Posted on Wed, 08 Sep 2021 01:45:20 -0400 by perrohunter