2.4 Log processing
2.4.1 Record log content
- Request url
- Visitor ip
- Call method classMethod
- Parameter args
- Return content
2.4.2 new package aspect, new log aspect processing class
package com.fei.aspect;import java.util.Arrays;import javax.servlet .http.HttpServletRequest;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.Signature;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj. lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component ;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;/** * Created by zxf on September 28, 2019*/@Aspect // Perform aspect operations @Component // Component scanning public class LogAspect {private final Logger logger = Logge rFactory.getLogger(this.getClass()); // Aspect @Pointcut("execution(* com.fei.controller.*.*(..))") public void log() {} // Aspect operation@ Before("log()") // transfer aspect method public void doBefore(JoinPoint joinPoint) {logger.info("---------doBefore------"); ServletRequestAttributes attributes = (ServletRequestAttributes ) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String url = request.getRequestURL().toString(); String ip = request.getRemoteAddr(); Signature signature = joinPoint.getSignature(); String classMethod = signature.getDeclaringTypeName() + "." + signature.getName(); Object[] args = joinPoint.getArgs(); RequestLog requestLog = new RequestLog(url, ip, classMethod, args); logger.info("Reqeust: { }", requestLog);} // post-aspect operation @After("log()") // transfer aspect method public void doAfter() {logger.info("---------doAfter--- ---");} // Operate after the section returns @Af terReturning(returning = "result", pointcut = "log()") // transfer aspect method public void doAfterReturn(Object result) {logger.info("Result: {}", result);} /** * Encapsulate the log Record what you need * * @author fei * */ private class RequestLog {private String url;// request url private String ip;// visitor ip private String classMethod;// call method private Object[] args;// parameters public RequestLog(String url, String ip, String classMethod, Object[] args) {super(); this.url = url; this.ip = ip; this.classMethod = classMethod; this.args = args;} @Override public String toString() {return "[url=" + url + ", ip=" + ip + ", classMethod=" + classMethod + ", args=" + Arrays.toString(args) + "]";} }/ / RequestLog}// LogAspect
Test log aspect processing Controller
@Controllerpublic class IndexController {@GetMapping("/{id}/{name}") publi c String toIndex(@PathVariable("id") Integer id, @PathVariable("name") String name) {System.out.println("====index() method execution ===="); return " index"; }}