初始化
This commit is contained in:
90
doc/基本框架设计/统一的系统日志.md
Normal file
90
doc/基本框架设计/统一的系统日志.md
Normal file
@@ -0,0 +1,90 @@
|
||||
## 系统日志
|
||||
|
||||
利用`spring`框架中`aop`,我们可以实现业务代码与系统级服务进行解耦,例如日志记录、事务及其他安全业务等,可以使得我们的工程更加容易维护、优雅。如何在系统中添加相应的日志呢?
|
||||
|
||||
##### 添加依赖
|
||||
|
||||
```
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-aop</artifactId>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
##### 自定义注解
|
||||
|
||||
```java
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface SysLog {
|
||||
String value() default "";
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
##### 配置切面
|
||||
|
||||
```java
|
||||
@Aspect
|
||||
@Component
|
||||
public class SysLogAspect {
|
||||
@Autowired
|
||||
private SysLogService sysLogService;
|
||||
private static Logger logger = LoggerFactory.getLogger(SysLogAspect.class);
|
||||
|
||||
@Around("@annotation(sysLog)")
|
||||
public Object around(ProceedingJoinPoint joinPoint,com.yami.shop.common.annotation.SysLog sysLog) throws Throwable {
|
||||
long beginTime = SystemClock.now();
|
||||
//执行方法
|
||||
Object result = joinPoint.proceed();
|
||||
//执行时长(毫秒)
|
||||
long time = SystemClock.now() - beginTime;
|
||||
|
||||
SysLog sysLogEntity = new SysLog();
|
||||
if(sysLog != null){
|
||||
//注解上的描述
|
||||
sysLogEntity.setOperation(sysLog.value());
|
||||
}
|
||||
|
||||
//请求的方法名
|
||||
String className = joinPoint.getTarget().getClass().getName();
|
||||
String methodName = joinPoint.getSignature().getName();
|
||||
sysLogEntity.setMethod(className + "." + methodName + "()");
|
||||
|
||||
//请求的参数
|
||||
Object[] args = joinPoint.getArgs();
|
||||
String params = Json.toJsonString(args[0]);
|
||||
sysLogEntity.setParams(params);
|
||||
|
||||
//设置IP地址
|
||||
sysLogEntity.setIp(IPHelper.getIpAddr());
|
||||
//用户名
|
||||
String username = SecurityUtils.getSysUser().getUsername();
|
||||
sysLogEntity.setUsername(username);
|
||||
sysLogEntity.setTime(time);
|
||||
sysLogEntity.setCreateDate(new Date());
|
||||
//保存系统日志
|
||||
sysLogService.save(sysLogEntity);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
将自定义的注解作为切入点,参数是`ProceedingJoinPoint`和`sysLog`,`ProceedingJoinPoint`用来获取当前执行的方法,`syslog`用来获取注解里面的值。
|
||||
|
||||
#### 在需要记录日志的方法上,添加注解`@SysLog(value)`
|
||||
|
||||
```java
|
||||
@SysLog("修改角色")
|
||||
@PutMapping
|
||||
@PreAuthorize("@pms.hasPermission('sys:role:update')")
|
||||
public ServerResponseEntity<Void> update(@RequestBody SysRole role){
|
||||
sysRoleService.updateRoleAndRoleMenu(role);
|
||||
return ServerResponseEntity.success();
|
||||
}
|
||||
```
|
||||
|
||||
当操作这个方法时,将会被记录到数据库中,在日志管理中能看到相应操作的内容。
|
||||

|
||||
Reference in New Issue
Block a user