add an aspect in Spring Boot
Maven
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
|
Enable/disable auto configuration
1
| spring.aop.auto = true //'false' disables the auto configuration
|
Creating aspects with @Aspect
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| package com.uuzu.newbasys.aspect;
import java.io.BufferedReader; import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import com.uuzu.newbasys.annotation.LogAPIAccessAnnotation; import com.uuzu.newbasys.mapper.ba.log.LogAPIAccessMapper; import com.uuzu.newbasys.model.log.LogAPIAccessModel;
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component;
import org.slf4j.Logger; import org.slf4j.LoggerFactory;
@Aspect @Component public class LogAPIAccessAspect {
private static final Logger logger = LoggerFactory.getLogger(LogAPIAccessAspect.class);
@Autowired private LogAPIAccessMapper mapper;
@Autowired private HttpServletRequest request;
ThreadLocal<LogAPIAccessModel> logModelTh = new ThreadLocal<>();
@Around("@annotation(com.uuzu.newbasys.annotation.LogAPIAccessAnnotation)") public Object logAPIAccess(ProceedingJoinPoint joinPoint) throws Throwable {
LogAPIAccessModel logModel = new LogAPIAccessModel(); logModelTh.set(logModel);
String userName = "anonymous";
if (SecurityContextHolder.getContext().getAuthentication() != null) { UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal(); userName = userDetails.getUsername(); }
String url = request.getRequestURL().toString(); String httpMethod = request.getMethod(); String ip = request.getRemoteAddr();
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); String className = methodSignature.getDeclaringTypeName(); String methodName = methodSignature.getName(); JSONObject params = new JSONObject(request.getParameterMap()); StringBuilder sb = new StringBuilder(); BufferedReader reader = request.getReader(); try { String line; while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } } finally { reader.close(); } String requestBody = null; if (sb.toString().length() > 0) { requestBody = sb.toString(); }
long start = System.currentTimeMillis();
Object proceed = joinPoint.proceed();
long executionTime = System.currentTimeMillis() - start;
LogAPIAccessAnnotation logAnnotation = method.getAnnotation(LogAPIAccessAnnotation.class); String logAnnotationValue = "-"; if (logAnnotation != null) { logAnnotationValue = logAnnotation.value(); } String[] logAnnotationValueArray = logAnnotationValue.split("-");
logModel.setUserName(userName); logModel.setProject(logAnnotationValueArray[0]); logModel.setPage(logAnnotationValueArray[1]); logModel.setDetail(logAnnotationValueArray[2]); logModel.setHttpMethod(httpMethod); logModel.setUrl(url); logModel.setExecutionTime(executionTime); logModel.setParams(params.toString()); logModel.setRequestBody(requestBody); logModel.setClassName(className); logModel.setMethodName(methodName); logModel.setIp(ip);
return proceed; }
@AfterReturning(pointcut = "@annotation(com.uuzu.newbasys.annotation.LogAPIAccessAnnotation)", returning = "response") public void doAfterReturning(Object response) throws Throwable {
LogAPIAccessModel logModel = logModelTh.get(); logModel.setResponse(response.toString());
try { mapper.save(logModel); } catch (Exception e) { logger.error("接口统计报错!"); logger.error(e.getMessage()); } finally { logModelTh.remove(); } } }
|
create annotation
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| package com.uuzu.newbasys.annotation;
import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.annotation.ElementType; import java.lang.annotation.RetentionPolicy;
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface LogAPIAccessAnnotation { String value() default ""; }
|
test
1 2 3 4 5 6 7
| @PostMapping("/logPostMethodTest") @LogAPIAccessAnnotation("yoobi-test-log") public Map<String, Object> logPostMethodTest(@RequestBody Map<String, Object> requestBody,@RequestParam("name") String name, @RequestParam("age") int age) {
return requestBody; }
|