Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How Spring Boot uses AOP to log

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you how Spring Boot uses AOP to record logs, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

In project development, the log system is often essential, especially the management system, there will be operation logs for important operations, but this operation does not need to be implemented one by one in the corresponding methods. This is certainly not appropriate, such an operation undoubtedly increases the amount of development, and is not easy to maintain. So in the actual project, AOP (Aspect Oriented Programming), that is, aspect-oriented programming, is always used to record the operation log in the system.

Here's how to use AOP to log in Spring Boot:

Add dependency

First, add AOP dependencies:

Org.springframework.boot spring-boot-starter-aop

Create a log annotation class

Create a log annotation class so that you can log by adding comments to the methods that need to be logged, as follows:

@ Target ({ElementType.PARAMETER, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documented public @ interface AopLogger {String describe () default ";}

Configure AOP section

Define an AopLoggerAspect facet class and declare it as a facet class with @ Aspect.

@ Component public class AopLoggerAspect {private final Logger logger = LoggerFactory.getLogger (this.getClass ()) @ Pointcut ("@ annotation (com.wupx.aop.logger.annotation.AopLogger)") public void aopLoggerAspect () {} / * * surround trigger * * @ param point * @ return * / @ Around ("aopLoggerAspect ()") public Object doAround (ProceedingJoinPoint point) {RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes (); ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes HttpServletRequest request = servletRequestAttributes.getRequest (); Object result = null; long startTime = System.currentTimeMillis (); try {result = point.proceed ();} catch (Throwable throwable) {throwable.printStackTrace (); logger.error (throwable.getMessage ());} String describe = getAopLoggerDescribe (point) If (StringUtils.isBlank (describe)) {describe = "-";} / print request related parameters logger.info ("= = Start = ="); logger.info ("Describe: {}", describe); / / print request url logger.info ("URL: {}", request.getRequestURL ()) Logger.info ("URI: {}", request.getRequestURI ()); / print Http method logger.info ("HTTP Method: {}", request.getMethod ()); / / print the full path of calling controller and the execution method logger.info ("Class Method: {}. {}", point.getSignature (). GetDeclaringTypeName (), point.getSignature (). GetName ()) / / print the requested IP logger.info ("IP: {}", request.getRemoteAddr ()); / / print the request input parameter logger.info ("Request Args: {}", point.getArgs ()); / / print the request output parameter logger.info ("Response Args: {}", result) Logger.info ("Time Consuming: {} ms", System.currentTimeMillis ()-startTime); logger.info ("= = End = ="); return result } / * get the description of the method in the comments * * @ param joinPoint pointcut * @ return describe * / public static String getAopLoggerDescribe (JoinPoint joinPoint) {MethodSignature signature = (MethodSignature) joinPoint.getSignature (); Method method = signature.getMethod (); AopLogger controllerLog = method.getAnnotation (AopLogger.class); return controllerLog.describe ();}}

"@ Pointcut" defines a pointcut, followed by an expression, which can be defined as a method under a package, a custom annotation, and so on.

"@ Around" weaves code before and after pointcuts, and is free to control when pointcuts are executed.

test

Next, write the Controller layer for testing:

@ RestController @ RequestMapping ("/ user") public class UserController {private final UserService userService; public UserController (UserService userService) {this.userService = userService;} @ PostMapping @ AopLogger (describe = "add users") public String addUser (@ RequestBody User user) {UserEntity userEntity = new UserEntity (); BeanUtils.copyProperties (user, userEntity); return userService.addUser (userEntity);}}

You only need to enter @ AopLogger on the interface to record the operation log.

Start the service and request the http://localhost:8080/user API through PostMan. The output log is as follows:

You can see that the input parameters, output parameters and interface information have been recorded, is not very simple, only a few simple steps can be achieved AOP log, you can practice under their own.

The complete code for this article is in the aop-logger directory of https://github.com/wupeixuan/SpringBoot-Learn.

The above is all the contents of the article "how Spring Boot uses AOP to log". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report