SpringBoot使用AOP全局日志

首先要加入依赖:

         
            org.springframework.boot
            spring-boot-starter-aop
        

我们沿用SpringBoot使用HikriCP数据源连接池整合Mybatis,MappperXML和Mapper注解混用版和Springboot配置logback日志----依葫芦画瓢就能用​​​​​​的mybatis和日志以及web的配置。

然后就是要写一个类定义切点和通知:

@Aspect
@Component
public class WebLogAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("execution(public * com.wangye.spbootaoplog.controller..*.*(..))")
    public void webLog(){

    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        Enumeration enu = request.getParameterNames();

        while (enu.hasMoreElements()) {
            String name = (String) enu.nextElement();
            logger.info("name:{},value:{}", name, request.getParameter(name));
        }
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求,返回内容
        logger.info("RESPONSE : " + ret);
    }
}

还是贴一贴controller吧:

@Controller
public class UserController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/getUserById1/{id}")
    @ResponseBody
    public User getUserById1(@PathVariable("id") Long id){
        return userService.getUserById1(id);
    }

    @RequestMapping("/getUserById/{id}")
    @ResponseBody
    public User getUserById(@PathVariable("id") Long id){
        return userService.getUserById(id);
    }
}

至于Service和Mapper还有user就自行按照笔者先前的博文进行配置吧。

对了,User实体类最好事先toString()方法,这样返回的参数就不会是一个类型加内存地址了。

测试一下其中一个地址:看看输出的日志

你可能感兴趣的:(框架技术)