spring boot项目中使用aop处理日志

2 篇文章 0 订阅
1 篇文章 0 订阅

spring boot项目中使用aop处理日志

spring boot中使用aop处理日志

在我们日常的开发中日志对于我们来说是十分重要的,那么今天我们就来聊聊spring boot中如何使用aop来处理我们的日志

一.maven导入和数据库的连接

1…新建spring boot项目导入maven依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

      
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

2.在application.yml中配置自己的数据源
在这里插入图片描述
3.连接数据库:可以任意选择一个写好的数据库,但是要和数据源一致
在这里插入图片描述

二.开始处理日志

1.WebAspect日志类的编写

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
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;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;


/**
 * @Author big dog
 * Date on 2020/6/23
 */
@Aspect
@Component
public class WebAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    ThreadLocal<Long> startTime = new ThreadLocal<>();
    @Pointcut("execution(public * com.dog.controller..*.*(..))")
    public void log(){
    }
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        startTime.set(System.currentTimeMillis());
        //接收到请求,记录请求内容
        ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpSession session = request.getSession();
        String url = request.getRequestURI().toString();
        String httpMethod = request.getMethod();
        Object[] args = joinPoint.getArgs();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName()+ "." + joinPoint.getSignature().getName();
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args, httpMethod);
        logger.info("日志"+":"+requestLog);
    }

    @AfterReturning(returning = "ret", pointcut = "log()")
    public void afterReturning(Object ret){
        //返回值
        logger.info("Response"+":"+ ret);
        logger.info("spend time"+":"+ (System.currentTimeMillis() - startTime.get()));
        startTime.remove();
    }
    @After("log()")
    public void doAfter(){
        logger.info("-------执行结束--------");
    }

    public class RequestLog{
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;
        private String httpMethod;

        public RequestLog(String url, String ip, String classMethod, Object[] args, String httpMethod) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
            this.httpMethod = httpMethod;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    ", httpMethod='" + httpMethod + '\'' +
                    '}';
        }
    }
}

2.Controller的编写

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @Author big dog
 * Date on 2020/6/23
 */
@Controller
@RequestMapping("/log")
public class LogController {
    @ResponseBody
    @RequestMapping("/index")
    public String log(){
        return "hello,world";
    }
}

三.测试

以上准备完成后,运行程序
访问http://localhost:8080/log/index
控制台日志打印如下:

2020-06-23 14:37:00.996  INFO 2072 --- [nio-8080-exec-1] com.dog.aspect.WebAspect                 : 日志:RequestLog{url='/log/index', ip='0:0:0:0:0:0:0:1', classMethod='com.dog.controller.LogController.log', args=[], httpMethod='GET'}
2020-06-23 14:37:01.001  INFO 2072 --- [nio-8080-exec-1] com.dog.aspect.WebAspect                 : Response:hello,world
2020-06-23 14:37:01.002  INFO 2072 --- [nio-8080-exec-1] com.dog.aspect.WebAspect                 : spend time:2097
2020-06-23 14:37:01.002  INFO 2072 --- [nio-8080-exec-1] com.dog.aspect.WebAspect                 : -------执行结束--------

今天的分享就这些喜欢的点赞收藏一下啦,也可以联系我一起学习和分享经验!

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值