0216 aop和打印数据库执行日志
2020/2/18 8:09:00
本文主要是介绍0216 aop和打印数据库执行日志,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
需求
maven依赖
<dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>3.8.7</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>28.2-jre</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
打印sql
配置要点:
- 驱动配置 application.properties
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/demo_datasource
- psy配置
# 单行日志 logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat # 使用Slf4J记录sql appender=com.p6spy.engine.spy.appender.Slf4JLogger # 是否开启慢SQL记录 outagedetection=true # 慢SQL记录标准,单位秒 outagedetectioninterval=2
aop打印持久层执行时间
使用aop实现;
package com.springbootpractice.demo.p6spy.aop; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import org.springframework.util.StopWatch; /** * 说明:aop配置 * @author carter * 创建时间: 2020年02月16日 8:49 下午 **/ @Aspect @Component @Slf4j public class PrintTimeCostAspectJConfig { @SneakyThrows @Around("myPointCut()") public Object around(ProceedingJoinPoint pj) { Object res = null; String methodName = pj.getSignature().toShortString(); StopWatch stopWatch = new StopWatch(methodName); stopWatch.start(); try { res = pj.proceed(); } catch (Throwable ex) { throw ex; } finally { stopWatch.stop(); log.warn("{}执行耗时{}毫秒", methodName, stopWatch.getTotalTimeMillis()); } return res; } @Pointcut("execution(* com.springbootpractice.demo.p6spy.web..*(..))") public void myPointCut() { } }
启用aop注解:
@EnableAspectJAutoProxy(proxyTargetClass = true)
小结
来个效果截图:
通过本片文章,你可以学会:
- 给代码添加aop切面,增加日志或者打印出方法执行总耗时;
- 给你的数据持久层打印出所有的sql语句,方便生产环境排查问题;
希望大家平安度过冠疫!每天持续精进!
本文由博客一文多发平台 OpenWrite 发布!
点击查看更多内容
这篇关于0216 aop和打印数据库执行日志的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-03万字长文聊聊Web3的组成架构
- 2024-07-02springboot项目无法注册到nacos-icode9专业技术文章分享
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?