In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "SpringBoot development how to use AOP logging", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "SpringBoot development how to use AOP logging" bar!
Why use AOP?
The answer is decoupling!
Aspect Oriented Programming is aspect-oriented programming. Decoupling is always pursued by programmers in the process of coding development. AOP is also born for decoupling.
The specific idea is: define a section, define the processing method longitudinally in the section, and return to the horizontal business flow after the processing is completed.
AOP is mainly realized by using the technology of agent mode.
A technology that realizes the unified maintenance of program functions through pre-compilation and runtime dynamic agents. Each part of the business logic can be isolated by using AOP, which reduces the coupling between the various parts of the business logic, improves the reusability of the program, and improves the efficiency of development at the same time.
Commonly used work scenarios
Transaction control
Log record
Concepts that must be known-terms related to AOP
Notification (Advice)
The notification describes the work to be done and when it will be performed. For example, if our log section needs to record the duration of each API call, we need to record the current time before and after the API call, and then take the difference.
Pre-notification (Before): invokes the notification function before the target method is called
Post notification (After): invokes the notification function after the target method is called, regardless of the result returned by the method
Return notification (AfterReturning): call the notification function after the target method executes successfully
Exception notification (AfterThrowing): calls the notification function after the target method throws an exception
Around: the notification wraps the target method and performs custom behavior before and after the target method call.
Connection point (JoinPoint)
When the notification function is applied. For example, the interface method is the connection point of the log section when it is called.
Tangent point (Pointcut)
The pointcut defines the scope to which the notification function is applied. For example, the scope of application of log aspects is all interfaces, that is, interface methods of all controller layers.
Section (Aspect)
Aspect is the combination of notification and pointcut, which defines when and where to apply the notification function.
Introduction (Introduction)
Add a new method or property to an existing class without modifying it.
Weave in (Weaving)
The process of applying a section to a target object and creating a new proxy object.
Create a section using annotations in Spring
Related notes
@ Aspect: used to define the section
@ Before: notifies the method to execute before the target method is called
@ After: the notification method executes after the target method returns or throws an exception
@ AfterReturning: the notification method executes after the target method returns
@ AfterThrowing: the notification method executes after the target method throws an exception
@ Around: the notification method encapsulates the target method
@ Pointcut: define a tangent expression
Tangent expression
Specifies the scope in which the notification is applied, and the expression format:
Execution (the method modifier returns the package to which the type method belongs. Class name. Method name (method parameters) / / public methods of all classes in the com.ninesky.study.tiny.controller package apply the notification execution (public * com.ninesky.study.tiny.controller.*.* (..)) / / all methods in all classes under the com.ninesky.study.tiny.service package and its subpackage apply the notification execution (* com.ninesky.study.tiny.service..*.* (..) / / All methods in the com.ninesky.study.tiny.service.PmsBrandService class apply the notification execution (* com.macro.ninesky.study.service.PmsBrandService.* (..)) in the aspect. Practical applications-logging with AOP
Change from the traditional industry, never thought of making a log burying place before, the first job, really should choose a good platform is more important.
Define log information encapsulation
Used to encapsulate the log information to be recorded, including the description of the operation, time, elapsed time, url, request parameters and return results, etc.
Public class WebLog {/ * Operation description * / private String description; / * Operation user * / private String username; / * Operation time * / private Long startTime; / * consumption time * / private Integer spendTime; / * Root path * / private String basePath / * URI * / private String uri; / * URL * / private String url; / * request type * / private String method; / * IP address * / private String ip; / * request parameters * / private Object parameter / * * the result returned by the request * / private Object result; / / omitted the getter,setter method}
Define annotations to reduce the amount of code through annotations
@ Documented@Retention (RetentionPolicy.RUNTIME) @ Target (ElementType.METHOD) public @ interface OperationLog {String name (); / / call the name of the API boolean intoDb () default false;// whether the operation log needs persistent storage} uniform log processing aspect @ Aspect@Component@Order (1) @ Slf4jpublic class WebLogAspect {private static final Logger controlLog = LoggerFactory.getLogger ("tmall_control") @ Pointcut ("execution (public * com.yee.walnut.* (..)") Public void webLog () {} @ Before (value = "webLog () & & @ annotation (OperationLog)") public void doBefore (ControllerWebLog controllerWebLog) throws Throwable {} @ AfterReturning (value = "webLog () & @ annotation (OperationLog)", returning = "ret") public void doAfterReturning (Object ret, ControllerWebLog controllerWebLog) throws Throwable {} @ Around (value = "webLog () & & @ annotation (OperationLog)") public Object doAround (ProceedingJoinPoint joinPoint) OperationLog operationLog) throws Throwable {long startTime = System.currentTimeMillis () / / get the current request object ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes (); HttpServletRequest request = attributes.getRequest (); / / record request information Object [] objs = joinPoint.getArgs (); WebLog webLog = new WebLog (); Object result = joinPoint.proceed () / / the result returned, which is a boundary between an entry method and an exit method Signature signature = joinPoint.getSignature (); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod (); long endTime = System.currentTimeMillis (); String urlStr = request.getRequestURL (). ToString (); webLog.setBasePath (urlStr, URLUtil.url (urlStr). GetPath ()) WebLog.setIp (request.getRemoteUser ()); webLog.setMethod (request.getMethod ()); webLog.setParameter (getParameter (method, joinPoint.getArgs (); webLog.setResult (JSONUtil.parse (result)); webLog.setSpendTime ((int) (endTime-startTime)); webLog.setStartTime (startTime); webLog.setUri (request.getRequestURI ()); webLog.setUrl (request.getRequestURL (). ToString ()) ControlLog.info ("RequestAndResponse {}", JSONObject.toJSONString (webLog)); / / must have this return value. It can be understood that after the Around method, instead of the value returned by the woven function, the return value of the Around function return result;} / * gets the request parameter * / private Object getParameter (Method method, Object [] args) {List argList = new ArrayList (); Parameter [] parameters = method.getParameters (); for (int I = 0) according to the method and the parameters passed in. I < parameters.length; annotations +) {/ / take the parameter modified by the RequestBody annotation as the request parameter RequestBody requestBody = parameters [I] .getAnnotation (RequestBody.class); if (requestBody! = null) {argList.add (args [I]) } / / take the parameter modified by the RequestParam annotation as the request parameter RequestParam requestParam = parameters [I] .getAnnotation (RequestParam.class); if (requestParam! = null) {Map map = new HashMap (); String key = parameters[ I] .getName () If (! StringUtils.isEmpty (requestParam.value () {key = requestParam.value ();} map.put (key, args [I]); argList.add (map);} else {argList.add (args [I]) }} if (argList.size () = = 0) {return null;} else if (argList.size () = = 1) {return argList.get (0);} else {return argList;}}
You can add custom comments to the method.
@ OperationLog (name = "TurnOnOffStrategy") public String doOperation (GlobalDto globalDto, DeviceOperator deviceOperator) {} Thank you for your reading. The above is the content of "how SpringBoot developers use AOP to log". After the study of this article, I believe you have a deeper understanding of how SpringBoot developers use AOP to log, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.