springboot利用@Aspect实现日志工具类的详细代码

目录

  • 一、导包
  • 二、在启动类上进行注解自动扫描
  • 三、工具类
  • 四、结果

一、导包
org.aspectjaspectjrt1.8.12org.aspectjaspectjweaver1.9.4


二、在启动类上进行注解自动扫描
@SpringBootApplication@EnableCaching@EnableAsync@ComponentScan({"com.workorder.*"})public class WorkOrderApplication {public static void main(String[] args) {SpringApplication.run(WorkOrderApplication.class, args); }}


三、工具类
@Aspect@Component@Slf4jpublic class LogAspect { @Autowired private Environment env; @Pointcut("execution(public * com.workorder..controller..*.*(..))")public void logPointCut(){}@Around("logPointCut()")public Object around(ProceedingJoinPoint point) throws Throwable {log.info("========================================="); long beginTime = System.currentTimeMillis(); //执行方法Object result = point.proceed(); //执行时长(毫秒)long time = System.currentTimeMillis() - beginTime; //保存日志saveSysLog(point, time); return result; }private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {// 接收到请求,记录请求内容ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String logStr=""; if (isEnvironment("dev")){String requestUrl = request.getRequestURL().toString() + "?"; //获取所有参数方法Enumeration enu=request.getParameterNames(); while(enu.hasMoreElements()){String paraName = enu.nextElement(); requestUrl+=paraName + "=" + request.getParameter(paraName) + "&"; }logStr+="\r\n请求地址:"+ requestUrl.substring(0,requestUrl.length()-1); }//请求的参数Object[] args = joinPoint.getArgs(); String params = JSONUtil.toJsonStr(args); logStr+="\r\n请求方式:"+ request.getMethod(); logStr+="\r\n请求方法Token:"+ request.getHeader("token"); logStr+="\r\n请求参数:"+params; logStr+="\r\nIP:"+ request.getRemoteAddr(); logStr+="\r\n响应时间:"+time+" ms"; log.info(logStr); /*** 判断当前是什么环境* @param str* @return*/ private boolean isEnvironment(String str) {boolean flag = false; String[] arr = env.getActiveProfiles(); List list = Arrays.asList(arr); if (list.contains(str)) {flag = true; }return flag; }}


四、结果 springboot利用@Aspect实现日志工具类的详细代码
文章图片

【springboot利用@Aspect实现日志工具类的详细代码】到此这篇关于springboot利用@Aspect实现日志工具类的详细代码的文章就介绍到这了,更多相关springboot日志工具类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读