springcloud專案搭建(五)----使用Spring aop完成統一日誌和異常管理
阿新 • • 發佈:2019-01-07
專案地址:https://gitee.com/lwydyby/springcloud-adplatform
注:由於專案初期搭建,暫未使用springcloud-sleuth進行追蹤分析,而是使用AOP進行統一的日誌記錄
1.編寫切面類
1).DisableGameleyLog為自定義註解,為了可以通過該註解跳過一些不必記錄的操作
2)目前只記錄controller層日誌
3)該攔截器除日誌記錄功能外,也進行了統一的異常處理,如丟擲異常,統一返回給介面500
4)由於將該配置儲存在公共的基礎common包中,只要引入common的所有專案都會預設在啟動時載入該配置,無需再進行單獨的配置。
package com.gameley.common.Interceptor;
import com.gameley.common.exception.BaseException;
import com.gameley.common.util.ClientUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory ;
import org.springframework.core.annotation.Order;
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 java.util .Arrays;
@Aspect
@Component
public class HttpAspect {
private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
@SuppressWarnings("unchecked")
@Pointcut("execution(public * com.gameley.controller.*.*(..)) && [email protected](com.gameley.common.DisableGameleyLog))")
public void log(){
}
@Before("log()")
public void doBefore(JoinPoint joinPoint){
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 記錄下請求內容
logger.info("請求地址 : " + request.getRequestURL().toString());
logger.info("HTTP METHOD : " + request.getMethod());
// 獲取真實的ip地址
logger.info("IP : " + ClientUtil.getClientIp(request));
logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
+ joinPoint.getSignature().getName());
logger.info("引數 : " + Arrays.toString(joinPoint.getArgs()));
}
@Around("log()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
try {
long startTime = System.currentTimeMillis();
Object ob= proceedingJoinPoint.proceed();
logger.info("耗時 : " + (System.currentTimeMillis() - startTime));
return ob;
} catch (Exception e) {
logger.error("error:",e);
return new BaseException("後臺操作異常",500);
}
}
@AfterReturning(pointcut = "log()",returning = "object")//列印輸出結果
public void doAfterReturing(Object object){
logger.info("response={}",object.toString());
}
}
2.編寫DisableGameleyLog自定義註解
package com.gameley.common;
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface DisableGameleyLog {
}
3.建立logback配置檔案(目前為從網上下載的模板,待使用後再修改)
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--
說明:
1、日誌級別及檔案
日誌記錄採用分級記錄,級別與日誌檔名相對應,不同級別的日誌資訊記錄到不同的日誌檔案中
例如:error級別記錄到log_error_xxx.log或log_error.log(該檔案為當前記錄的日誌檔案),而log_error_xxx.log為歸檔日誌,
日誌檔案按日期記錄,同一天內,若日誌檔案大小等於或大於2M,則按0、1、2...順序分別命名
例如log-level-2013-12-21.0.log
其它級別的日誌也是如此。
2、檔案路徑
若開發、測試用,在Eclipse中執行專案,則到Eclipse的安裝路徑查詢logs資料夾,以相對路徑../logs。
若部署到Tomcat下,則在Tomcat下的logs檔案中
3、Appender
FILEERROR對應error級別,檔名以log-error-xxx.log形式命名
FILEWARN對應warn級別,檔名以log-warn-xxx.log形式命名
FILEINFO對應info級別,檔名以log-info-xxx.log形式命名
FILEDEBUG對應debug級別,檔名以log-debug-xxx.log形式命名
stdout將日誌資訊輸出到控制上,為方便開發測試使用
-->
<contextName>userservice</contextName>
<property name="LOG_PATH" value="/home" />
<!--設定系統日誌目錄-->
<property name="APPDIR" value="userService" />
<!-- 日誌記錄器,日期滾動記錄 -->
<appender name="FILEERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在記錄的日誌檔案的路徑及檔名 -->
<file>${LOG_PATH}/${APPDIR}/log_error.log</file>
<!-- 日誌記錄器的滾動策略,按日期,按大小記錄 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 歸檔的日誌檔案的路徑,例如今天是2013-12-21日誌,當前寫的日誌檔案路徑為file節點指定,可以將此檔案與file指定檔案路徑設定為不同路徑,從而將當前日誌檔案或歸檔日誌檔案置不同的目錄。
而2013-12-21的日誌檔案在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 -->
<fileNamePattern>${LOG_PATH}/${APPDIR}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<!-- 除按日誌記錄之外,還配置了日誌檔案不能超過2M,若超過2M,日誌檔案會以索引0開始,
命名日誌檔案,例如log-error-2013-12-21.0.log -->
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>2MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<!-- 追加方式記錄日誌 -->
<append>true</append>
<!-- 日誌檔案的格式 -->
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>===%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
<charset>utf-8</charset>
</encoder>
<!-- 此日誌檔案只記錄info級別的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>error</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 日誌記錄器,日期滾動記錄 -->
<appender name="FILEWARN" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在記錄的日誌檔案的路徑及檔名 -->
<file>${LOG_PATH}/${APPDIR}/log_warn.log</file>
<!-- 日誌記錄器的滾動策略,按日期,按大小記錄 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 歸檔的日誌檔案的路徑,例如今天是2013-12-21日誌,當前寫的日誌檔案路徑為file節點指定,可以將此檔案與file指定檔案路徑設定為不同路徑,從而將當前日誌檔案或歸檔日誌檔案置不同的目錄。
而2013-12-21的日誌檔案在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 -->
<fileNamePattern>${LOG_PATH}/${APPDIR}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<!-- 除按日誌記錄之外,還配置了日誌檔案不能超過2M,若超過2M,日誌檔案會以索引0開始,
命名日誌檔案,例如log-error-2013-12-21.0.log -->
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>2MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<!-- 追加方式記錄日誌 -->
<append>true</append>
<!-- 日誌檔案的格式 -->
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>===%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
<charset>utf-8</charset>
</encoder>
<!-- 此日誌檔案只記錄info級別的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 日誌記錄器,日期滾動記錄 -->
<appender name="FILEINFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在記錄的日誌檔案的路徑及檔名 -->
<file>${LOG_PATH}/${APPDIR}/log_info.log</file>
<!-- 日誌記錄器的滾動策略,按日期,按大小記錄 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 歸檔的日誌檔案的路徑,例如今天是2013-12-21日誌,當前寫的日誌檔案路徑為file節點指定,可以將此檔案與file指定檔案路徑設定為不同路徑,從而將當前日誌檔案或歸檔日誌檔案置不同的目錄。
而2013-12-21的日誌檔案在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 -->
<fileNamePattern>${LOG_PATH}/${APPDIR}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<!-- 除按日誌記錄之外,還配置了日誌檔案不能超過2M,若超過2M,日誌檔案會以索引0開始,
命名日誌檔案,例如log-error-2013-12-21.0.log -->
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>2MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<!-- 追加方式記錄日誌 -->
<append>true</append>
<!-- 日誌檔案的格式 -->
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>===%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
<charset>utf-8</charset>
</encoder>
<!-- 此日誌檔案只記錄info級別的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>info</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!--encoder 預設配置為PatternLayoutEncoder-->
<encoder>
<pattern>===%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
<charset>utf-8</charset>
</encoder>
<!--此日誌appender是為開發使用,只配置最底級別,控制檯輸出的日誌級別是大於或等於此級別的日誌資訊-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>debug</level>
</filter>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.hibernate" level="WARN" />
<!-- 生產環境下,將此級別配置為適合的級別,以免日誌檔案太多或影響程式效能 -->
<root level="INFO">
<appender-ref ref="FILEERROR" />
<appender-ref ref="FILEWARN" />
<appender-ref ref="FILEINFO" />
<!-- 生產環境將請stdout,testfile去掉 -->
<appender-ref ref="STDOUT" />
</root>
</configuration>