AOP的日志获取

在学习系统权限权限项目时,需要将用户在web层的请求操作的信息提取出来,作为日志信息存储到数据库中,整体的思路就是对web层的所有实例对象的所有方法做一个AOP切面,当Spring MVC前端控制器调用实例对象内的方法时,就会触发切面对应的通知类,并执行里面的通知方法

日志的实体类

1
2
3
4
5
6
7
8
9
10
public class SysLog {
private String id;
private Date visitTime;//访问的时间
private String visitTimeStr;
private String username;//访问用户名
private String ip;//访问者的IP
private String url;//访问者的url
private Long executionTime;//访问执行的时间
private String method;//访问的方法接口
}

日志AOP通知类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@Controller
@Aspect
public class LogAop {

@Autowired
private HttpServletRequest request;
@Autowired
private SysLogService sysLogService;
private Date visitTime;//访问时间

//配置一个切入点
@Pointcut("execution(* controller.*.*(..))")
public void pointcut(){};

//配置方法执行前操作
@Before("pointcut()")
public void before(JoinPoint joinPoint) throws NoSuchMethodException {
//获取访问时间
visitTime = new Date();
}

//配置方法执行后操作,除访问时间,其他操作都放在后置
@After("execution(* controller.*.*(..))")
public void afterReturning(JoinPoint joinPoint){
//获取执行的时间
Long executionTime = new Date().getTime() - visitTime.getTime();
//获取访问用户名
String username = ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
//获取访问的类路径
Class excutionClass = joinPoint.getTarget().getClass();
//获取访问的方法
String methodName = joinPoint.getSignature().getName();
//获取访问的IP
String ip = request.getRemoteAddr();
//获取访问的url路径
String url = request.getRequestURL().toString();

//将上述的信息存储到SysLog,并存储到数据库
SysLog sysLog = new SysLog();
sysLog.setExecutionTime(executionTime);
sysLog.setIp(ip);
sysLog.setMethod(excutionClass.getName()+"."+methodName);
sysLog.setUrl(url);
sysLog.setUsername(username);
sysLog.setVisitTime(visitTime);
sysLogService.save(sysLog);
}
}
打赏