在pom中引入依赖:
<!--AOP-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
创建AOP类:
@Aspect
@Configuration
public class LogAop {
private Logger logger = LoggerFactory.getLogger(getClass());
@Pointcut("execution(public * com.example.springboot.test..*.*(..))")
public void webLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
logger.info("URL : " + request.getRequestURL().toString());
logger.info("HTTP_METHOD : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr());
Enumeration<String> enu = request.getParameterNames();
while (enu.hasMoreElements()) {
String name = (String) enu.nextElement();
logger.info("name:{},value:{}", name, request.getParameter(name));
}
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
logger.info("RESPONSE : " + ret);
}
}
或者在有标记的注解上使用:
@Target(ElementType.METHOD) //注解放置的目标位置,METHOD是可注解在方法级别上
@Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行
@Documented //生成文档
public @interface MyLog {
String value() default "";
}
//定义切点 @Pointcut
//在注解的位置切入代码
@Pointcut("@annotation( com..annotation.MyLog)")
public void logPoinCut() {
}
@AfterReturning("logPoinCut()")
public void saveSysLog(JoinPoint joinPoint) {
System.out.println("切面");
//保存日志
SysLog sysLog = new SysLog();
sysLog.setId(RecordNoUtils.getUniqueIdBySnakeflow());
//从切面织入点处通过反射机制获取织入点处的方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//获取切入点所在的方法
Method method = signature.getMethod();
//获取操作
MyLog myLog = method.getAnnotation(MyLog.class);
if (myLog != null) {
String value = myLog.value();
sysLog.setOperation(value);//保存获取的操作
}
//获取请求的类名
String className = joinPoint.getTarget().getClass().getName();
//获取请求的方法名
String methodName = method.getName();
sysLog.setMethod(className + "." + methodName);
//请求的参数
Object[] args = joinPoint.getArgs();
//需要过滤掉request和response
List<Object> logArgs = StreamUtil.streamOf(args)
.filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)))
.collect(Collectors.toList());
String params= JSON.toJSONString(logArgs);
sysLog.setParams(params);
sysLog.setCreateDate(new Date());
//获取用户名
//此例子用到了ShiroUtils框架来实现获取用户名,此处还可以用session来获取登录操作名
//例:HttpSession session=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getSession();
sysLog.setUserName(UserContext.getUser()==null?"ImefutureSystem"
:UserContext.getUser().getUserName());
//获取用户ip地址
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
sysLog.setIp(IpUtil.getIpAddr(request));
//调用service保存SysLog实体类到数据库
sysLogService.saveSysLog(sysLog);
}