本文旨在实现注解式操作日志记录:
实现步骤:
1、定义注解式接口:
OperationLog.java:
/**
* 标记需要记录操作日志的方法
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface OperationLog {
/**
* 业务名称,如:"修改雇员"
*/
String value() default "";
/**
* 被修改的实体的唯一标识,如:雇员ID
*/
String key() default "";
}
2、定义切面:
OptLogAop.java:
/**
* 操作日志AOP
*/
@Aspect
@Component
public class OptLogAop {
@Pointcut(value = "@annotation(com.test.log.OperationLog)")
public void cutMothod() {
}
@AfterReturning(value = "cutMothod()", returning = "returnValue")
public void afterHandle(JoinPoint point, DSResponse returnValue) throws Exception {
// 获取拦截的方法
Signature sig = point.getSignature();
if (!(sig instanceof MethodSignature)) {
throw new IllegalArgumentException("该注解只可用于方法!");
}
MethodSignature mSig = (MethodSignature) sig;
Object target = point.getTarget();
Method currentMethod = target.getClass().getMethod(mSig.getName(), mSig.getParameterTypes());
// 若当前用户未登录,则不记录操作日志
User user = AuthUtils.getCurrentUser();
if (user == null) {
return;
}
// 获取操作名称
OperationLog annotation = currentMethod.getAnnotation(OperationLog.class);
String key = annotation.key();
String[] paramNames = mSig.getParameterNames();
StringBuilder sb = new StringBuilder();
Object paramValue = null;
if (!QString.isNullOrEmpty(key) && paramNames.length != 0) {
for (int i = 0; i < paramNames.length; i++) {
if (key.equals(paramNames[i])) {
paramValue = point.getArgs()[i];
}
}
sb.append(key + ":" + paramValue);
}
String optBus = annotation.value();
String ipAddress = ApUtil.getClientIp(ApUtil.getRequest());
// 船舰
OptLogFactory.createOptLog(user, optBus, sb.toString(), returnValue, ipAddress);
}
}
3、创建日志记录,保存至数据库:
OptLogFactory.java:
public class OptLogFactory {
private static OptLogService optLogService = AppContext.getBean(OptLogService.class);
private static Logger logger = LoggerFactory.getLogger(OptLogFactory.class);
public static void createOptLog(User user, String optBus, String optKeyWord,
DSResponse returnValue, String ipAddress) {
OptLog optLog = new OptLog();
try {
optLog.setOptUserName(user.getUserName());
optLog.setOptUserDept(user.getDeptName());
optLog.setOptBus(optBus);
optLog.setIpAddress(ipAddress);
optLog.setOptKeyWord(optKeyWord);
optLog.setOptResult(returnValue.getStatus());
optLog.setOptTime(System.currentTimeMillis());
optLog.setRemarks(StringUtils.join(returnValue.getMessage(), ","));
optLogService.save(optLog);
} catch (Exception e) {
logger.error("创建操作日志异常!", e);
}
}
}
4、注解的使用:
在涉及到增删改的方法上添加@OperationLog注解即可。
@OperationLog(value = "修改用户", key = "userId")
public DSResponse updateUser(String userId){
···
}