springboot 使用Aop 记录系统日志steemCreated with Sketch.

in #springboot7 years ago

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);

}

Sort:  

Interesting
I will follow you to see your future posts! +UP

Congratulations @yunfei! You received a personal award!

1 Year on Steemit

Click here to view your Board of Honor

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @yunfei! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

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!

Coin Marketplace

STEEM 0.20
TRX 0.14
JST 0.030
BTC 67978.59
ETH 3270.89
USDT 1.00
SBD 2.65