注解切面保存日志
符号
阅读:646
2021-04-01 11:08:02
评论:0
1.创建自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
String value() default "";
}
2.切面处理类(落库日志)
/**
* 系统日志,切面处理类
*
*/
@Aspect
@Component
public class SysLogAspect {
@Autowired
private SupLogService supLogService;
@Pointcut("@annotation(bw.yth.svc.common.annotation.SysLog)")
public void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
// 执行方法
Object result = point.proceed();
// 执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
// 保存日志
saveSysLog(point, time);
return result;
}
private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 获取用户信息
String token = request.getHeader(AppConst.HEADER_TOKEN);
SessionData session = AppBuffer.bufSession.getSession(token);
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
SupLogPO supLog = new SupLogPO();
SysLog syslog = method.getAnnotation(SysLog.class);
if (syslog != null) {
// 注解上的描述
supLog.setOperation(syslog.value());
}
// 请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
supLog.setMethod(className + "." + methodName + "()");
// 请求的参数
Object[] args = joinPoint.getArgs();
try {
String params = JSONObject.toJSONString(args);
supLog.setParam(params);
} catch (Exception e) {
}
long userId = 0;
if (session != null) {
SysUserPO user = session.getUser();
userId = user.getUserId();
// 设置IP地址
supLog.setIp(session.getClientIp());
// 客户端系统
EnClientSystem clientSystem = session.getClientSystem();
supLog.setClientType(clientSystem.id());
// 业务系统
EnSvcSystem svcSystem = session.getSvcSystem();
supLog.setSysId(svcSystem.id());
}
// 用户id
supLog.setUserId(userId);
// 保存系统日志
supLogService.save(supLog);
}
}
3.controller方法加注解
@SysLog("测试时间格式化")
@PostMapping("/testDate")
@ApiOperation(value="测试时间格式化", notes="")
public TestResVo login2(@RequestBody TestReqVo req)
{
System.out.println(JSONObject.toJSONString(req));
LocalDateTime date = req.getDate();
LocalDateTime plusHours = date.plusHours(2);
TestResVo resVo = new TestResVo();
resVo.setDate(plusHours);
resVo.setId(18);
return resVo;
}
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。