How to use @ Aspect to implement logging tool class in springboot
This article mainly introduces springboot how to use @ Aspect to achieve logging tool class related knowledge, the content is detailed and easy to understand, simple and fast operation, has a certain reference value, I believe that after reading this springboot how to use @ Aspect to achieve logging tool class article will have a harvest, let's take a look at it.
First, guide package org.aspectj aspectjrt 1.8.12 org.aspectj aspectjweaver 1.9.4 II. Automatically scan @ SpringBootApplication@EnableCaching@EnableAsync@ComponentScan ({"com.workorder.*"}) public class WorkOrderApplication {public static void main (String [] args) {SpringApplication.run (WorkOrderApplication.class, args);}} third, tool class @ Aspect@Component@Slf4jpublic class LogAspect {@ Autowired private Environment env @ Pointcut ("execution (public * com.workorder..controller..*.* (..)") Public void logPointCut () {} @ Around ("logPointCut ()") public Object around (ProceedingJoinPoint point) throws Throwable {log.info ("= ="); long beginTime = System.currentTimeMillis (); / / execution method Object result = point.proceed (); / / execution duration (Ms) long time = System.currentTimeMillis ()-beginTime / / Save the log saveSysLog (point, time); return result;} private void saveSysLog (ProceedingJoinPoint joinPoint, long time) {/ / receive the request and record the request content ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes (); HttpServletRequest request = attributes.getRequest (); String logStr= "" If (isEnvironment ("dev")) {String requestUrl = request.getRequestURL (). ToString () + "?"; / / get all parameter methods Enumeration enu=request.getParameterNames (); while (enu.hasMoreElements ()) {String paraName = enu.nextElement () RequestUrl+=paraName + "=" + request.getParameter (paraName) + "&";} logStr+= "\ r\ nrequest address:" + requestUrl.substring (0questUrl.length ()-1);} / / request parameter Object [] args = joinPoint.getArgs (); String params = JSONUtil.toJsonStr (args) LogStr+= "\ r\ nrequest method:" + request.getMethod (); logStr+= "\ r\ nrequest method Token:" + request.getHeader ("token"); logStr+= "\ r\ nrequest parameters:" + params; logStr+= "\ r\ nIP:" + request.getRemoteAddr (); logStr+= "\ r\ nResponsive time:" + time+ "ms"; log.info (logStr) / * determine what the current environment is * @ param str * @ return * / private boolean isEnvironment (String str) {boolean flag = false; String [] arr = env.getActiveProfiles (); List list = Arrays.asList (arr) If (list.contains (str)) {flag = true;} return flag;} IV. Result
This is the end of the article on "how springboot uses @ Aspect to implement logging tool classes". Thank you for reading! I believe you all have a certain understanding of "how springboot uses @ Aspect to achieve logging tools". If you want to learn more, you are welcome to follow the industry information channel.