1.创建注解
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperLog {
/**
* 模块
*/
public String title() default "";
/**
* 功能
*/
public BusinessType businessType() default BusinessType.OTHER;
/**
* 操作人类别
*/
public OperatorType operatorType() default OperatorType.MANAGE;
/**
* 是否保存请求的参数
*/
public boolean isSaveRequestData() default true;
/**
* 是否保存响应的参数
*/
public boolean isSaveResponseData() default true;
/**
* 排除指定的请求参数
*/
public String[] excludeParamNames() default {};
}
2.AOP
@Aspect
@Component
public class OperLogAspect{
public static final Logger log= LoggerFactory.getLogger(OperLog.class);
@AfterReturning(pointcut = "@annotation(operLog)",returning = "jsonResult")
private void doAfterReturning(JoinPoint joinPoint, OperLog operLog,Object jsonResult){
//方法正常运行 无问题
handleLog(joinPoint,operLog,null,jsonResult);
}
@AfterThrowing(pointcut = "@annotation(operLog)",throwing = "e")
private void doAfterThrowing(JoinPoint joinPoint, OperLog operLog,Exception e){
//方法报错
handleLog(joinPoint,operLog,e,null);
}
//操作日志存库 操作失败有exception 操作成功有jsonResult
private void handleLog(final JoinPoint joinPoint, OperLog operLog, Exception e,Object jsonResult){
SysOperLog data = new SysOperLog();
data.setStatus(BusinessStatus.SUCCESS.ordinal());
// 请求的地址
LoginUser loginUser = SecurityUtils.getLoginUser();
String ip = IpUtils.getIpAddr();
data.setOperIp(ip);
data.setOperUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
if (loginUser != null)
{
data.setOperName(loginUser.getUsername());
SysUser currentUser = loginUser.getUser();
if (StringUtils.isNotNull(currentUser) && StringUtils.isNotNull(currentUser.getDept()))
{
data.setDeptName(currentUser.getDept().getDeptName());
}
}
//记录方法有异常
if (e != null)
{
data.setStatus(BusinessStatus.FAIL.ordinal());
data.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
}
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
data.setMethod(className + "." + methodName + "()");
// 设置请求方式
data.setRequestMethod(ServletUtils.getRequest().getMethod());
// 设置action动作
data.setBusinessType(operLog.businessType().ordinal());
// 设置标题
data.setTitle(operLog.title());
// 设置操作人类别
data.setOperatorType(operLog.operatorType().ordinal());
// 远程查询操作地点
data.setOperLocation(AddressUtils.getRealAddressByIP(data.getOperIp()));
// 操作结果
data.setJsonResult(StringUtils.substring(JSON.toJSONString(jsonResult), 0, 2000));
//保存操作日志
SpringUtils.getBean(ISysOperLogService.class).insertOperlog(data);
}
}