環境:IDEA版本2017.3.1 x64, JDK1.8, SpringBoot2.1.1, Druid1.1.8, mybatis1.3.2,Security5.1.2,thymeleaf3.0.11java
思路總結:首先在須要作日誌記錄的方法中添加一個自定義註解,再去實現一個日誌AOP類,AOP類把自定義註解設置爲切點,因此當系統執行某一個添加了自定義註解的方法時,AOP會自動獲取該方法名稱以及用戶信息實現日誌記錄。nginx
/**
* 自定義註解類 定義controller方法的中文含義
* @Target({METHOD,TYPE}) 表示這個註解能夠用用在類/接口上,還能夠用在方法上
* @Retention(RetentionPolicy.RUNTIME) 表示這是一個運行時註解,即運行起來以後,才獲取註解中的相關信息,而不像基本註解如@Override 那種不用運行,在編譯時eclipse就能夠進行相關工做的編譯時註解。
* @Inherited 表示這個註解能夠被子類繼承
* @Documented 表示當執行javadoc的時候,本註解會生成相關文檔
*/
@Target({METHOD, TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Operation {
String value() default "";
}
複製代碼
日誌AOP類會用到獲取IP地址的工具類,也用到json工具類,實現工具類以下web
/**
* 獲取用戶真實的ip地址
* @param request
* @return
*/
public class IpAdrressUtil {
public static String getIpAdrress(HttpServletRequest request) {
String ip = null;
//X-Forwarded-For:Squid 服務代理
String ipAddresses = request.getHeader("X-Forwarded-For");
String unknown = "unknown";
if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
//Proxy-Client-IP:apache 服務代理
ipAddresses = request.getHeader("Proxy-Client-IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
//WL-Proxy-Client-IP:weblogic 服務代理
ipAddresses = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
//HTTP_CLIENT_IP:有些代理服務器
ipAddresses = request.getHeader("HTTP_CLIENT_IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
//X-Real-IP:nginx服務代理
ipAddresses = request.getHeader("X-Real-IP");
}
//有些網絡經過多層代理,那麼獲取到的ip就會有多個,通常都是經過逗號(,)分割開來,而且第一個ip爲客戶端的真實IP
if (ipAddresses != null && ipAddresses.length() != 0) {
ip = ipAddresses.split(",")[0];
}
//仍是不能獲取到,最後再經過request.getRemoteAddr();獲取
if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
複製代碼
public class JacksonUtil {
private final static ObjectMapper objectMapper = new ObjectMapper();
private JacksonUtil() {
}
public static ObjectMapper getInstance() {
return objectMapper;
}
/**
* javaBean、列表數組轉換爲json字符串
*/
public static String obj2json(Object obj) throws Exception {
return objectMapper.writeValueAsString(obj);
}
/**
* json 轉JavaBean
*/
public static <T> T json2pojo(String jsonString, Class<T> clazz) throws Exception {
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
return objectMapper.readValue(jsonString, clazz);
}
/**
* json字符串轉換爲map
*/
public static <T> Map<String, Object> json2map(String jsonString) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.readValue(jsonString, Map.class);
}
}
複製代碼
/**
* 系統日誌:切面處理類
*/
@Aspect
@Component
public class SysLogAspect {
@Autowired
private SysLogService sysLogService;
//定義切點 @Pointcut
//在註解的位置切入代碼
@Pointcut("@annotation(cn.springboot.util.Operation)")
public void logPoinCut() {
}
//切面 配置通知
@AfterReturning("logPoinCut()")
public void saveSysLog(JoinPoint joinPoint) {
//保存日誌
SysLog sysLog = new SysLog();
//從切面織入點處經過反射機制獲取織入點處的方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//獲取切入點所在的方法
Method method = signature.getMethod();
//獲取操做
Operation operation = method.getAnnotation(Operation.class);
if (operation != null) {
String value = operation.value();
sysLog.setOperation(value);//保存獲取的操做
}
//獲取請求的類名
String className = joinPoint.getTarget().getClass().getName();
//獲取請求的方法名
String methodName = method.getName();
sysLog.setMethod(className + "." + methodName);
//請求的參數
Object[] args = joinPoint.getArgs();
//將參數所在的數組轉換成json
String params = null;
try {
params = JacksonUtil.obj2json(args);
} catch (Exception e) {
e.printStackTrace();
}
sysLog.setParams(params);
//請求的時間
sysLog.setCreateDate(new Date());
//獲取用戶名
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
sysLog.setUsername(authentication.getName());
}
//獲取用戶ip地址
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
sysLog.setIp(IpAdrressUtil.getIpAdrress(request));
//調用service保存SysLog實體類到數據庫
sysLogService.saveLog(sysLog);
}
}
複製代碼
最後,我是調用service保存SysLog實體類到數據庫,你也能夠直接輸出到控制檯,要保存到數據庫,還要實現service類,mapper類和javeBean。 我就簡單貼個javaBean,其餘類就不具體貼出了。spring
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SysLog implements Serializable {
private Long id;
private String username; //用戶名
private String operation; //操做
private String method; //方法名
private String params; //參數
private String ip; //ip地址
private Date createDate; //操做時間
//建立getter和setter方法
}
複製代碼
javaBean中使用lombok的註解實現了get、set等方法。數據庫
如下是存進數據庫的數據,關於IP的問題是由於本地測試,部署在服務器上就會有正常的IP地址了。apache
更多Spring Boot整合可瀏覽此博客:malizhi.cnjson