您好,登錄后才能下訂單哦!
這篇文章主要介紹了springboot怎么利用@Aspect實現日志工具類的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇springboot怎么利用@Aspect實現日志工具類文章都會有所收獲,下面我們一起來看看吧。
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.12</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency>
@SpringBootApplication @EnableCaching @EnableAsync @ComponentScan({"com.workorder.*"}) public class WorkOrderApplication { public static void main(String[] args) { SpringApplication.run(WorkOrderApplication.class, args); } }
@Aspect @Component @Slf4j public 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<String> 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<String> list = Arrays.asList(arr); if (list.contains(str)) { flag = true; } return flag; } }
關于“springboot怎么利用@Aspect實現日志工具類”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“springboot怎么利用@Aspect實現日志工具類”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。