javascript
Spring Boot 入门(五):集成 AOP 进行日志管理
本篇文章是接著 Spring boot 入門(四):集成 Shiro 實現登陸認證和權限管理寫的,按照前面幾篇博客的教程,可以搭建一個簡單的項目,主要包含了 Pagehelper+MyBatis 分頁查詢,Generator 代碼自動生成器,Shiro登錄及權限管理。本篇博客主要是集成 AOP 進行日志管理
1.導入 jar 包
<!-- aop --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency> 復制代碼2.配置 Logback-spring 文件
關于 Logback-spring 的配置網上很多,隨便copy一份基本上就能使用,Logback-spring.xml 中主要配置了下列內容
- (1).日志寫道控制臺
- (2).日志寫道本地文件中
- (3).日志級別
- (4).日志生成方式(按照日期滾動生成,還是按照日期單獨生成)
- (5).日志來源的配置,一般直接配置到 Control
我也是直接在copy了一份,代碼如下
<?xml version="1.0" encoding="UTF-8"?> <configuration scan="true" scanPeriod="60 seconds" debug="false"><contextName>logback</contextName> <!--<!– 文件輸出格式 –><property name="PATTERN" value="%-12(%d{yyyy-MM-dd HH:mm:ss.SSS}) |-%-5level [%thread] %c [%L] -| %msg%n" /><!– test文件路徑 –><property name="TEST_FILE_PATH" value="c:/log" />--><!--輸出到控制臺--><appender name="console" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>%d{HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern></encoder></appender><!--按天生成日志--><appender name="logFile" class="ch.qos.logback.core.rolling.RollingFileAppender"><Prudent>true</Prudent><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><FileNamePattern>applog/%d{yyyy-MM-dd}/%d{yyyy-MM-dd}.log</FileNamePattern></rollingPolicy><layout class="ch.qos.logback.classic.PatternLayout"><Pattern>%d{yyyy-MM-dd HH:mm:ss} -%msg%n</Pattern></layout></appender><logger name="com.tswc.edu" additivity="false"><appender-ref ref="console"/><appender-ref ref="logFile" /></logger><root level="error"><appender-ref ref="console"/><appender-ref ref="logFile" /></root></configuration>復制代碼這里用戶也可以配置多個級別使用于多個環境,對每個日志級別進行配置不同的屬性,然后在 Application.xml 中選擇不同的級別環境。在實際項目開發的過程中,一般配置2個環境,開發環境,生產環境。在開發環境中,只需要配置日志輸出到控制臺,便于開發人員調試。生成環境相反,需要配置日志輸出到文件,控制臺盡量不要輸出日志,這樣可以減少控制臺對虛擬機內存的消耗,一旦產生 Bug ,用戶查詢日志文件即可
上述代碼中即配置了日志輸出到控制臺,也配置了日志輸出到日志文件
3.配置日志級別
只需要在 Application.xml 中配置即可:
日志級別分為5個等級,debug<info<warn<Error<Fatal,其中常用的級別為:debug和info- debug 級別最低,可以隨意的使用于任何覺得有利于在調試時更詳細的了解系統運行狀態的東東;
- info 重要,輸出信息:用來反饋系統的當前狀態給最終用戶的; 后三個,警告、錯誤、嚴重錯誤,這三者應該都在系統運行時檢測到了一個不正常的狀態。
- warn, 可修復,系統可繼續運行下去;
- Error, 可修復性,但無法確定系統會正常的工作下去;
- Fatal, 相當嚴重,可以肯定這種錯誤已經無法修復,并且如果系統繼續運行下去的話后果嚴重。
4.編寫日志類
@Aspect @Component public class WebLogAspect {private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);@Pointcut("execution( * com.tswc.edu.controller.*.*(..))")//兩個..代表所有子目錄,最后括號里的兩個..代表所有參數public void logPointCut() {}//切點@Pointcut("@annotation(com.tswc.edu.annotation.Log)")public void logPointCutLog() {}@Before("logPointCut()")public void doBefore(JoinPoint joinPoint) throws Throwable {// 接收到請求,記錄請求內容ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();// 記錄下請求內容logger.info("請求地址 : " + request.getRequestURL().toString());//logger.info("方法描述 : " + );logger.info("HTTP METHOD : " + request.getMethod());// 獲取真實的ip地址//logger.info("IP : " + IPAddressUtil.getClientIpAddress(request));logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."+ joinPoint.getSignature().getName());logger.info("參數 : " + Arrays.toString(joinPoint.getArgs())); // loggger.info("參數 : " + joinPoint.getArgs());}@AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的參數名一致public void doAfterReturning(Object ret) throws Throwable {// 處理完請求,返回內容(返回值太復雜時,打印的是物理存儲空間的地址)logger.debug("返回值 : " + ret);}@Around("logPointCut()")public Object doAround(ProceedingJoinPoint pjp) throws Throwable {long startTime = System.currentTimeMillis();Object ob = pjp.proceed();// ob 為方法的返回值logger.info("耗時 : " + (System.currentTimeMillis() - startTime));return ob;}@Around("logPointCutLog()")public Object around(ProceedingJoinPoint point) throws Throwable {// 執行方法Object result = point.proceed();// 獲得注解Log controllerLog = getAnnotationLog(point);if (controllerLog == null) {return null;}String action = controllerLog.value();logger.info("請求目的:"+action);return result;}/*** 是否存在注解,如果存在就獲取*/private static Log getAnnotationLog(JoinPoint joinPoint) throws Exception {Signature signature = joinPoint.getSignature();MethodSignature methodSignature = (MethodSignature) signature;Method method = methodSignature.getMethod();if (method != null) {//System.out.println("123:"+method.getAnnotation(Log.class).value());return method.getAnnotation(Log.class);}//System.out.println("1234:"+method.getAnnotation(Log.class).value());return null;} } 復制代碼這是個通用類,主要約定控制臺或者日志文件中日志的格式,關于此公共類,網上有大量的講解,這里就不詳細說明了。
再次啟動項目,控制臺將輸出日志,并將日志寫入到文件中:
5.新增加部分
其中自定義日志文件可以不要,這里用戶自己定義了日志輸出的說明部分 自定義了 @Log 注記的識別,并配置一些文件說明,那么在請求到這個類的時候,日志中將輸出文章描述部分自定義配置文件的代碼:
- Log
- LogAspect
其中LogAspect中也可以寫一些對日志進行 CRUD 的業務邏輯操作,大多數情況下,此處可以將日志的保存邏輯寫入到此類中。
6.問題
本項目在啟動的時候,報了一個關于日志的警告,沒有找到解決方案
項目中并沒有用到log4j,不知道為什么會警告,項目中缺少log4j的配置文件,如果有大神知道原因,歡迎留言
總結
以上是生活随笔為你收集整理的Spring Boot 入门(五):集成 AOP 进行日志管理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软考自查:数据库设计
- 下一篇: laravel 框架的 csrf