package com.example.api.aspect; import com.example.api.annotation.Log; import com.example.api.model.entity.SystemLog; import com.example.api.service.SystemLogService; import com.example.api.utils.IpUtil; import com.example.api.utils.JwtTokenUtil; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; import java.time.LocalDateTime; @Aspect @Component public class LogAspect { @Autowired private SystemLogService logService; /* 表明切点 */ @Pointcut("@annotation(com.example.api.annotation.Log)") public void pt(){} /* 环绕通知 */ @Around("pt()") public Object Around(ProceedingJoinPoint point) throws Throwable { //记录开始时间 long beginTime = System.currentTimeMillis(); Object res = null; try { //执行方法 res = point.proceed(); }finally { //计算执行时长 long time = System.currentTimeMillis() - beginTime; recordLog(point); } return res; } private void recordLog(ProceedingJoinPoint point){ //获取当前请求对象 ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = requestAttributes.getRequest(); //获取目标方法签名 MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); Log annotation = method.getAnnotation(Log.class); //封装日志对象 SystemLog systemLog = new SystemLog(); systemLog.setModule(annotation.moudle()); systemLog.setBusincessType(annotation.type().getName()); systemLog.setIp(IpUtil.getIpAddr(request)); systemLog.setTime(LocalDateTime.now()); //获取方法的全路径 systemLog.setMethod(signature.getDeclaringTypeName()+"."+signature.getName()); //获取token,并解析token来获取当前账号 String token = request.getHeader(JwtTokenUtil.TOKEN_HEADER); systemLog.setAccount(JwtTokenUtil.getUsername(token)); //持久化到数据库 logService.record(systemLog); } }
最近下载更多
wsgwly LV5
9小时前
南乔木 LV8
4月24日
2716804680 LV9
4月20日
txf123 LV4
4月8日
陈小灏 LV14
4月6日
玖零定制问题修复 LV34
4月4日
微信网友_6927932988952576 LV12
3月30日
xiaozhi丶 LV14
3月24日
周青松 LV3
3月24日
Rommel LV27
3月23日
最近浏览更多
qizl LV8
6小时前
wsgwly LV5
9小时前
shooack
10小时前
暂无贡献等级
1477807783
4月30日
暂无贡献等级
kenhomeliu LV29
4月30日
1941549176
4月29日
暂无贡献等级
250930499 LV2
4月29日
周青松197 LV3
4月26日
hmf1989
4月26日
暂无贡献等级
南乔木 LV8
4月24日