Aop实现操作日志入库管理
程序员文章站
2022-04-25 19:31:16
...
Aop实现操作日志入库管理
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
自定义日志注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
String value() default "";
}
日志切面
@Around("@annotation(sysLog)")
public Object around(ProceedingJoinPoint joinPoint, com.xj.annotation.SysLog sysLog) throws Throwable {
long beginTime = System.currentTimeMillis();
//执行方法
Object result = joinPoint.proceed();
// 执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
int maxId = systemLogService.selectMaxId();
SystemLog systemLog = new SystemLog();
systemLog.setOperationTime(time);
if(sysLog != null){
//注解上的描述
systemLog.setAction(sysLog.value());
}
//编号
systemLog.setId(maxId+1);
//请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
systemLog.setNode(className + "." + methodName + "()");
//请求的参数
String [] paramNames = ((CodeSignature)joinPoint.getSignature()).getParameterNames();
Object[] args = joinPoint.getArgs();
Stream<?> stream = ArrayUtils.isEmpty(args) ? Stream.empty() : Arrays.stream(args);
List<Object> logArgs = stream
.filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)))
.collect(Collectors.toList());
String content = "";
for (int i = 0;i < args.length; i++){
if (args[i] instanceof MultipartFile){
content += "[{MultipartFile:'"+MultipartToFile((MultipartFile)args[i]).getName()+"'}";
}else{
content += JSON.toJSON(args[i]);
}
}
systemLog.setContent(content);
systemLog.setContent(content);
// systemLog.setParams(params);
//设置IP地址
// systemLog.setIp(IPHelper.getIpAddr());
//用户名
String ip = SecurityUtils.getSubject().getSession().getHost();
String userCode = SecurityUtils.getSubject().getPrincipals().toString();
systemLog.setIp(ip);
systemLog.setUserCode(userCode);
systemLog.setCreateTime(new Date());
//保存系统日志
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
logger.info(sdf.format(systemLog.getCreateTime()));
logger.info(systemLog.getIp()+":"+systemLog.getUserCode()+":"+systemLog.getNode()+":"+systemLog.getAction()+":"+systemLog.getContent());
systemLogService.save(systemLog);
return result;
}
Controller
@PostMapping("/uploadSampling")
@ApiOperation(value = "上传布点采样方案文件", notes = "上传布点采样方案文件", httpMethod = "POST")
@SneakyThrows
@SysLog("上传布点采样方案文件")
public ReturnResult uploadSampling(@ApiParam(value = "上传文件",required = true) @RequestParam("fileList") MultipartFile fileList){
}