AOP integration of SpringBoot, recording system log

The Spring Boot2. x version incorporates AOP and implements system logging through custom annotations

Add the dependent

Aop-related dependencies for introducing SpringBoot in POM

        <! -- Spring AOP -->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-aop</artifactId>

        </dependency>

Copy the code

SysLog is scheduled for the log entity class

@Table(name = "sys_log")

@Entity

@Data

@ApiModel(value = "Log Entity Class")

public class SysLog {

    @Id

   // @GeneratedValue(strategy = GenerationType.AUTO)

    private String id;

    / * *

* the name of the class

* * /


    @Column(nullable = false)

    private String className;



    / * *

* the method name

* * /


    @Column(nullable = false)

    private String methodName;



    / * *

* parameters

* * /


    @Column(nullable = false)

    private String params;



    / * *

* Execution time

* * /


    @Column(nullable = false)

    private Long execTime;



    / * *

* Section marks

* * /


    private String remark;



    / * *

* Creation time

* * /


    @Column(nullable = false)

    private String createDate;



    / * *

* request URL

* * /


    @Column(nullable = false)

    private String url;



    / * *

* request IP

* * /


    @Column(nullable = false)

    private String ip;



    / * *

     * http method

* * /


    @Column(nullable = false)

    private String httpMethod;



}

Copy the code

Custom annotation @syslogAnnotation

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface SysLogAnnotation {

    String value(a) default "";

}



Copy the code

The @aspect annotation declares an Aspect

@Aspect

@Component

public class SysLogAspect {

    @Autowired

    private SysLogService sysLogService;





    / * *

* Here we use the form of annotations

* Of course, we can also directly specify the package to intercept, the class to intercept, and the method to intercept via the pointcut expression

* Execution (...)

* such as execution (public * com. Example. Demo. Controller. *. * (..) )

* /


    @Pointcut("@annotation(com.gaolei.app.anno.SysLogAnnotation)")

    public void logPointCut(a) {}



    / * *

* Surround notification@AroundOf course, it can also be used@Before(Pre-notification)@After(Post notification)

     * @param point

     * @return

     * @throws Throwable

* /


    @Around("logPointCut()")

    public Object around(ProceedingJoinPoint point) throws Throwable {

        long beginTime = System.currentTimeMillis();

        Object result = point.proceed();

        long time = System.currentTimeMillis() - beginTime;

        try {

            saveLog(point, time);

        } catch (Exception e) {

        }

        return result;

    }



    / * *

* Save logs

     * @param joinPoint

     * @param time

* /


    private void saveLog(ProceedingJoinPoint joinPoint, long time) {

        SysLog sysLog = new SysLog();

        // Get the request URL, IP,httpMethod

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();

        String ip = request.getRemoteAddr();

        String httpMethod = request.getMethod();

        String url = request.getRequestURL().toString();

        sysLog.setIp(ip);

        sysLog.setHttpMethod(httpMethod);

        sysLog.setUrl(url);

        sysLog.setId(UUIDGenerator.generate());



        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        Method method = signature.getMethod();



        sysLog.setExecTime(time);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        sysLog.setCreateDate(dateFormat.format(new Date()));

        SysLogAnnotation annotation = method.getAnnotation(SysLogAnnotation.class);

        if(annotation ! =null) {

            // The description in the annotation

            sysLog.setRemark(annotation.value());

        }

        // Request class name, method name

        String className = joinPoint.getTarget().getClass().getName();

        String methodName = signature.getName();

        sysLog.setClassName(className);

        sysLog.setMethodName(methodName);

        // Request parameters

        Object[] args = joinPoint.getArgs();

        try{

            List<String> list = new ArrayList<String>();

            for (Object o : args) {

                list.add(new Gson().toJson(o));

            }

            sysLog.setParams(list.toString());

        }catch (Exception e){ }

        sysLogService.saveSysLog(sysLog);

    }



}

Copy the code

Define the service

public interface SysLogService {



    boolean saveSysLog(SysLog sysLog);

}

Copy the code

Define serviceImpl

@Slf4j

@Service

public class SysLogServiceImpl  implements SysLogService {

    @Autowired

    private SysLogRepository sysLogRepository;



    @Override

    public boolean saveSysLog(SysLog sysLog){

        sysLogRepository.save(sysLog);

// log.info(sysLog.getParams());

        log.info("Success");

        return true;

    }



}

Copy the code

## define TestController TestController

@Api(tags = "Test")

@Controller

@RequestMapping(value = "/test/v1")

public class TestController {



    @SysLogAnnotation("Section test")

    @GetMapping("/test")

    public String test(@RequestParam("name") String name){

        return name;

    }



}

Copy the code

test

http://localhost:9999/test/v1/test?name=gaolei
Copy the code
  • Idea breakpoint view

  • Viewing a Database

Blog source:Gitee/Duebasslei