1.自定义日志注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
// 业务类型
BusinessType businessType() default BusinessType.OTHER;
// 模块名称
String title() default "";
}
2.增加业务注解操作类型
public enum BusinessType {
/**
* 其它
*/
OTHER,
/**
* 新增
*/
INSERT,
/**
* 修改
*/
UPDATE,
/**
* 删除
*/
DELETE,
/**
* 授权
*/
GRANT,
}
3.切面方法
@Aspect
@Component
public class LogAspect {
@Autowired
HttpServletRequest httpServletRequest;
@Autowired
SysLogDao sysLogDao;
private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
/**
* 定义切面
*/
@Pointcut("@annotation(com.common.anno.Log)")
public void pt() {
}
/**
* 环绕切点
*/
@Around("pt()")
public Object log(ProceedingJoinPoint pjp) throws Throwable {
long beginTime = System.currentTimeMillis();
// 执行切点方法M
Object result = pjp.proceed();
// 执行时长
Long runTime = System.currentTimeMillis() - beginTime;
// 记录日志
handleLog(pjp,runTime,result);
return result;
}
private void handleLog(ProceedingJoinPoint pjp,Long runTime, Object result) {
MethodSignature signature = (MethodSignature)
pjp.getSignature();
Method method = signature.getMethod();
// 获取注解内容
Log logAnnotation = method.getAnnotation(Log.class);
// 获取模块
String title = logAnnotation.title();
// 获取业务类型
BusinessType businessType = logAnnotation.businessType();
Object[] args = pjp.getArgs();
// 入参数
String params = JSON.toJSONString(args);
//出参
String res = JSON.toJSONString(result);
// 请求方法
String httpMenthod = httpServletRequest.getMethod();
// ip
String ip = IPUtils.getIpAddr(httpServletRequest);
// 请求url
String requestURL = httpServletRequest.getRequestURL().toString();
// 封装日志对象
SysLog sysLog = new SysLog(title, businessType, httpMenthod, requestURL, ip, params, res, runTime);
// 这里可以根据自己的需求去处理sysLog
sysLogDao.insert(sysLog);
}
}
4.实际使用
@RequestMapping("/saveUser")
@Log(title = "新建用户" ,businessType = BusinessType.INSERT)
public R saveUser(){
}