SpringBoot引入AOP记录用户日志
效果
2020-07-28 09:32:16-[INFO]-[] 切面--前置通知
【请求方法:com.resource.ResourceManagerController.getResourceRel】
【方法描述:根据ID查询资源信息】
【请求人:admin】
【请求IP:169.254.124.120】
【参数:["1281069637315870720"]】
前提
application.yml配置
spring:
aop:
proxy-target-class: true
auto: true
自定义注解
import java.lang.annotation.*;
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemControllerLog {
String description() default "";
}
import java.lang.annotation.*;
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemServiceLog {
String description() default "";
}
切面【注:复制粘贴报错的方法根据自己已有的工具类进行改造】
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
@Aspect
@Component
@SuppressWarnings("all")
public class SystemLogAspect {
//Service层切点
@Pointcut("@annotation(com.common.annotate.SystemServiceLog)")
public void serviceAspect() {
}
//Controller层切点
@Pointcut("@annotation(com.common.annotate.SystemControllerLog)")
public void controllerAspect() {
}
/**
* 前置通知
*
* @param joinPoint
*/
@Before("controllerAspect()")
public void doBefore(JoinPoint joinPoint) {
try {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String user_name = "unKnow";
String ip = "unKnow";
if (request != null && request.getSession() != null) {
user_name = CasJsonUtil.getLoginNo(request.getSession());
}
if (request != null) {
ip = getIpAddress(request);
}
Object[] args = null;
Object[] arguments = null;
if (joinPoint != null) {
args = joinPoint.getArgs();
}
if (args != null) {
arguments = new Object[args.length];
}
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
continue;
}
arguments[i] = args[i];
}
String params = JSONObject.toJSONString(arguments);
LogUtils.restLogger.info("切面--前置通知\r\n" + "{}", "【请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()) + "】\r\n【方法描述:" + getControllerMethodDescription(joinPoint) + "】\r\n【请求人:" + user_name + "】\r\n【请求IP:" + ip + "】\r\n【参数:" + params + "】");
} catch (Exception e) {
LogUtils.restLogger.info("切面--前置通知异常" + "{}", e.getMessage());
}
}
/**
* 异常通知 用于拦截service层记录异常日志
*
* @param joinPoint
* @param e
*/
@AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
try {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String user_name = "unKnow";
String ip = "unKnow";
if (request != null && request.getSession() != null) {
user_name = CasJsonUtil.getLoginNo(request.getSession());
}
if (request != null) {
ip = getIpAddress(request);
}
Object[] args = null;
Object[] arguments = null;
if (joinPoint != null) {
args = joinPoint.getArgs();
}
if (args != null) {
arguments = new Object[args.length];
}
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
continue;
}
arguments[i] = args[i];
}
String params = JSONObject.toJSONString(arguments);
LogUtils.restLogger.info("切面--异常通知\r\n" + "{}", "【异常代码:" + e.getClass().getName() + "】\r\n【异常信息:" + e.getMessage() + "】\r\n【异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()") + "】\r\n【方法描述:" + getServiceMethodDescription(joinPoint) + "】\r\n【请求人:" + user_name + "】\r\n【请求IP:" + ip + "】\r\n【请求参数:" + params + "】");
} catch (Exception ex) {
LogUtils.restLogger.info("切面--异常通知--异常" + "{}", e.getMessage());
}
}
/**
* 获取注解中对方法的描述信息 用于service层注解
*
* @param joinPoint
* @return
* @throws Exception
*/
public static String getServiceMethodDescription(JoinPoint joinPoint) throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String description = "";
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
description = method.getAnnotation(SystemServiceLog.class).description();
break;
}
}
}
return description;
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
*
* @param joinPoint
* @return
* @throws Exception
*/
public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();//目标方法名
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String description = "";
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
description = method.getAnnotation(SystemControllerLog.class).description();
break;
}
}
}
return description;
}
private String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
if (ip.equals("127.0.0.1")
|| ip.equals("0:0:0:0:0:0:0:1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
if (inet != null) {
ip = inet.getHostAddress();
}
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ip != null && ip.length() > 15) { // "***.***.***.***".length()
// = 15
if (ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(","));
}
}
return ip;
}
}
使用
@RequestMapping("/getResourceRel")
@ResponseBody
@SystemControllerLog(description = "根据ID查询资源信息")
public ServiceRes<List<MalltRightsResourceRel>> getResourceRel(String resourceId) {
return null;
}
@Override
@SystemServiceLog(description = "查询资源是否打包")
public BusiResp<List<MalltRightsResourceRel>> getResourceRel(String resourceId) {
return null;
}