Created
June 21, 2019 10:52
-
-
Save chris-peng-1244/33889fbfeee5b7ff846a30e1e52d0d1b to your computer and use it in GitHub Desktop.
Spring AOP PostRequeustLogger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @Component | |
| @Aspect | |
| public class PostRequestLogger { | |
| @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)") | |
| public void postAction() { | |
| } | |
| @Before("postAction()") | |
| public void logAction(JoinPoint joinPoint) { | |
| Class clazz = joinPoint.getTarget().getClass(); | |
| Logger logger = LoggerFactory.getLogger(clazz); | |
| String url = getRequestUrl(joinPoint, clazz); | |
| String payload = getPayload(joinPoint); | |
| logger.info("POST " + url + " Payload " + payload); | |
| } | |
| private String getRequestUrl(JoinPoint joinPoint, Class clazz) { | |
| MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); | |
| Method method = methodSignature.getMethod(); | |
| PostMapping methodPostMapping = method.getAnnotation(PostMapping.class); | |
| RequestMapping requestMapping = (RequestMapping) clazz.getAnnotation(RequestMapping.class); | |
| return getPostUrl(requestMapping, methodPostMapping); | |
| } | |
| private String getPayload(JoinPoint joinPoint) { | |
| CodeSignature signature = (CodeSignature) joinPoint.getSignature(); | |
| StringBuilder builder = new StringBuilder(); | |
| for (int i = 0; i < joinPoint.getArgs().length; i++) { | |
| String parameterName = signature.getParameterNames()[i]; | |
| builder.append(parameterName); | |
| builder.append(": "); | |
| builder.append(joinPoint.getArgs()[i].toString()); | |
| builder.append(", "); | |
| } | |
| return builder.toString(); | |
| } | |
| private String getPostUrl(RequestMapping requestMapping, PostMapping postMapping) { | |
| String baseUrl = getUrl(requestMapping.value()); | |
| String endpoint = getUrl(postMapping.value()); | |
| return baseUrl + endpoint; | |
| } | |
| private String getUrl(String[] urls) { | |
| if (urls.length == 0) return ""; | |
| else return urls[0]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment