1、引入依赖
spring-boot-starter-aop
2、添加自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
3、添加拦截代码
@Aspect
@Component
public class LogAspect {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
SysLogService sysLogService;
@Pointcut("execution(public * com.demo.controller..(..))") //com.demo.controller..(..)) ..表示查找所有controller目录
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;
// 保存日志
saveLog(point, time);
return result;
}
private void saveLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
SysLog sysLog = new SysLog();
Log syslog = method.getAnnotation(Log.class);
if (syslog != null) {
// 注解上的描述
sysLog.setOperation(syslog.value());
}
// 请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
sysLog.setMethod(className + "." + methodName + "()");
// 获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
// 请求的参数
sysLog.setParams(CombaCommonUtil.jsonParseString(request.getParameterMap()));
//设置请求路径
sysLog.setUri(request.getRequestURI());
// 设置IP地址
sysLog.setIp(IPUtils.getIpAddr(request));
sysLog.setTime((int) time);
// 系统当前时间
Date date = new Date();
sysLog.setCreateTime(date);
// 保存系统日志
sysLogService.save(sysLog);
}
Interesting
I will follow you to see your future posts! +UP
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations @yunfei! You received a personal award!
Click here to view your Board of Honor
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations @yunfei! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Vote for @Steemitboard as a witness to get one more award and increased upvotes!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit